> 文章列表 > SSM框架的整合—图书管理的增删改查

SSM框架的整合—图书管理的增删改查

SSM框架的整合—图书管理的增删改查

系列文章目录

本节主要讲述SSM框架的整合技术和使用SSM开发的一个图书管理系统


文章目录

  • 系列文章目录
  • 前言
  • 一.SSM整合
  • 二、表现层数据封装
  • 三、异常处理器
  • 四、项目异常处理方案
  • 五、案例:SSM整合标准开发
  • 六、整体项目代码
    • 1.前期准备
      • 1.项目结构
      • 2.所需的pom依赖
      • 3.前端页面资料和SQL文件
    • 2.配置类
      • 1.JdbcConfig 配置数据源和添加事务管理
      • 2.MybatisConfig 类 ——Mybatis相关配置
      • 3.ServletConfig 类——Servlet相关配置
      • 4.SpringConfig 类——Spring相关配置
      • 5.SpringMvcConfig 类——SpringMVC相关配置
      • 6.SpringMvcSupport 类——释放所有静态资源
    • 3.数据层
      • 1.Mapper接口代理文件
      • 2.实体类
    • 4.业务层
      • 1.接口类
      • 2.接口实现类
    • 5.控制层
      • 1.业务处理类
      • 2.前后端数据交换规范类
      • 3.具体编码类
      • 4.异常处理类(统一在表现层处理)
    • 6.自定义异常类
      • 1.业务处理异常类(自定义)
      • 2.系统异常类(自定义)
    • 7.前端页面
    • 8.业务层端口单元测试类
  • 总结

前言

本节中用到的资料
链接:https://pan.baidu.com/s/1tSUMxH7G3-BX9MNnoVSw6Q?pwd=1111
提取码:1111


一.SSM整合

SSM框架的整合—图书管理的增删改查
SSM框架的整合—图书管理的增删改查
SSM框架的整合—图书管理的增删改查

SSM框架的整合—图书管理的增删改查
SSM框架的整合—图书管理的增删改查

二、表现层数据封装

  • 前端接收数据格式一 创建结果模型类,封装数据到data属性中
  • 前端接收数据格式一封装操作结果到code属性中
  • 前端接收数据格式一封装特殊消息到message (msg)属性中

SSM框架的整合—图书管理的增删改查
SSM框架的整合—图书管理的增删改查
SSM框架的整合—图书管理的增删改查

三、异常处理器

SSM框架的整合—图书管理的增删改查
SSM框架的整合—图书管理的增删改查

SSM框架的整合—图书管理的增删改查
SSM框架的整合—图书管理的增删改查
SSM框架的整合—图书管理的增删改查

四、项目异常处理方案

SSM框架的整合—图书管理的增删改查
SSM框架的整合—图书管理的增删改查
SSM框架的整合—图书管理的增删改查

SSM框架的整合—图书管理的增删改查
SSM框架的整合—图书管理的增删改查

SSM框架的整合—图书管理的增删改查
SSM框架的整合—图书管理的增删改查
SSM框架的整合—图书管理的增删改查

五、案例:SSM整合标准开发

SSM框架的整合—图书管理的增删改查

六、整体项目代码

1.前期准备

1.项目结构

SSM框架的整合—图书管理的增删改查

SSM框架的整合—图书管理的增删改查

2.所需的pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>springmvc-08-ssm</artifactId><version>1.0-SNAPSHOT</version><packaging>war</packaging><dependencies><!--SpringMVC相关jar包--><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.3.21</version></dependency><!--数据库连接池jar包--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.15</version></dependency><!--mybatis的jar包--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.9</version></dependency><!--mysql的jar包--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.29</version></dependency><!--spring操作数据库的包--><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.3.21</version></dependency><!--spring整合mybatis的包 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.7</version></dependency><!--junit的jar包--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency><!--spring整合Junit的jar包--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.3.21</version></dependency><!--Servlet相关jar包--><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version></dependency><!--JSON转化的jar包--><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.13.3</version></dependency></dependencies>
</project>

3.前端页面资料和SQL文件

在前言中有SQL文件和ssm相关的前端文件

2.配置类

1.JdbcConfig 配置数据源和添加事务管理

package org.example.config;import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;import javax.sql.DataSource;public class JdbcConfig {@Value("${jdbc.driver}")private String drive;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Beanpublic DataSource dataSource(){DruidDataSource ds=new DruidDataSource();ds.setDriverClassName(drive);ds.setUrl(url);ds.setUsername(username);ds.setPassword(password);return ds;}@Beanpublic PlatformTransactionManager transactionManager(DataSource dataSource){DataSourceTransactionManager dataSourceTransactionManager=new DataSourceTransactionManager();dataSourceTransactionManager.setDataSource(dataSource);return dataSourceTransactionManager;}
}

2.MybatisConfig 类 ——Mybatis相关配置

package org.example.config;import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;import javax.sql.DataSource;public class MybatisConfig {//定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象@Beanpublic SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){SqlSessionFactoryBean ssfb=new SqlSessionFactoryBean();ssfb.setTypeAliasesPackage("org.example.domain");ssfb.setDataSource(dataSource);return ssfb;}//定义bean,返回MapperScannerConfigurer对象@Beanpublic MapperScannerConfigurer mapperScannerConfigurer(){MapperScannerConfigurer msc=new MapperScannerConfigurer();msc.setBasePackage("org.example.dao");return msc;}
}

3.ServletConfig 类——Servlet相关配置

package org.example.config;import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {protected Class<?>[] getRootConfigClasses() {return new Class[]{SpringConfig.class};}protected Class<?>[] getServletConfigClasses() {return new Class[]{SpringMvcConfig.class};}protected String[] getServletMappings() {return new String[]{"/"};}
}

4.SpringConfig 类——Spring相关配置

package org.example.config;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;@Configuration
@ComponentScan("org.example.service")
@PropertySource("classpath:jdbc.properties")
@Import({MybatisConfig.class,JdbcConfig.class})
@EnableTransactionManagement
public class SpringConfig {
}

5.SpringMvcConfig 类——SpringMVC相关配置

package org.example.config;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;@Configuration
@ComponentScan({"org.example.controller","org.example.config"})
@EnableWebMvc
public class SpringMvcConfig {
}

6.SpringMvcSupport 类——释放所有静态资源

package org.example.config;import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {@Overrideprotected void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");registry.addResourceHandler("/js/**").addResourceLocations("/js/");registry.addResourceHandler("/css/**").addResourceLocations("/css/");registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");}
}

3.数据层

1.Mapper接口代理文件

package org.example.dao;import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.example.domain.Book;import java.util.List;public interface BookDao {@Insert("insert into tbl_book(type,name,description) values(#{type},#{name},#{description})")int save(Book book);@Update("update tbl_book set type=#{type},name=#{name},description=#{description} where id =#{id}")int update(Book book);@Delete("delete from tbl_book where id = #{id}")int delete(Integer id);@Select("select * from tbl_book where id = #{id}")Book getById(Integer id);@Select("select * from tbl_book")List<Book> getAll();
}

2.实体类

package org.example.domain;public class Book {private int id;private String type;private String name;private String description;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getType() {return type;}public void setType(String type) {this.type = type;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}@Overridepublic String toString() {return "Book{" +"id=" + id +", type='" + type + '\\'' +", name='" + name + '\\'' +", description='" + description + '\\'' +'}';}
}

4.业务层

1.接口类

package org.example.service;import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.example.domain.Book;
import org.springframework.transaction.annotation.Transactional;import java.util.List;@Transactional
public interface BookService {/*** 新增数据* @param book*/boolean save(Book book);/*** 修改数据* @param book*/boolean update(Book book);/*** 根据id删除数据* @param id*/boolean delete(Integer id);/*** 根据id查询数据* @param id* @return*/Book getById(Integer id);/*** 查询所有数据* @return*/List<Book> getAll();
}

2.接口实现类

package org.example.service.impl;import org.example.controller.Code;
import org.example.dao.BookDao;
import org.example.domain.Book;
import org.example.exception.BusinessException;
import org.example.exception.SystemException;
import org.example.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class BookServiceImpl implements BookService {@Autowiredprivate BookDao bookDao;public boolean save(Book book) {return bookDao.save(book) > 0;}public boolean update(Book book) {return bookDao.update(book) > 0;}public boolean delete(Integer id) {return bookDao.delete(id) > 0;}public Book getById(Integer id) {if (id < 0) {throw new BusinessException(Code.PROJECT_BUSINESS_ERR, "请勿违法操作");}return bookDao.getById(id);}public List<Book> getAll() {return bookDao.getAll();}
}

5.控制层

1.业务处理类

package org.example.controller;import org.apache.ibatis.annotations.Delete;
import org.example.domain.Book;
import org.example.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/books")
public class BookController {@Autowiredprivate BookService bookService;@PostMappingpublic Result save(@RequestBody Book book) {boolean flag = bookService.save(book);return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);}@PutMappingpublic Result update(@RequestBody Book book) {boolean flag = bookService.update(book);return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);}@DeleteMapping("/{id}")public Result delete(@PathVariable Integer id) {boolean flag = bookService.delete(id);return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, flag);}@GetMapping("/{id}")public Result getById(@PathVariable Integer id) {Book book = bookService.getById(id);Integer code = book != null ? Code.GET_OK : Code.GET_ERR;String msg = book != null ? "" : "数据查询失败,请重试";return new Result(code, book, msg);}@GetMappingpublic Result getAll() {List<Book> books = bookService.getAll();Integer code = books != null ? Code.GET_OK : Code.GET_ERR;String msg = books != null ? "" : "数据查询失败,请重试";return new Result(code, books, msg);}
}

2.前后端数据交换规范类

package org.example.controller;public class Result {private Object data;private Integer code;private String msg;public Result() {}public Result(Integer code,Object data) {this.data = data;this.code = code;}public Result( Integer code, Object data,String msg) {this.data = data;this.code = code;this.msg = msg;}public Object getData() {return data;}public void setData(Object data) {this.data = data;}public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}@Overridepublic String toString() {return "Result{" +"data=" + data +", code=" + code +", msg='" + msg + '\\'' +'}';}
}

3.具体编码类

package org.example.controller;public class Code {public static final Integer SAVE_OK=20011;public static final Integer DELETE_OK=20021;public static final Integer UPDATE_OK=20031;public static final Integer GET_OK=20041;public static final Integer SAVE_ERR=20010;public static final Integer DELETE_ERR=20020;public static final Integer UPDATE_ERR=20030;public static final Integer GET_ERR=20040;public static final Integer SYSTEM_UNKNOW_ERR=50001;public static final Integer SYSTEM_TIMEOUT_ERR=50002;public static final Integer PROJECT_VALIDATE_ERR=60001;public static final Integer PROJECT_BUSINESS_ERR=60002;
}

4.异常处理类(统一在表现层处理)

package org.example.controller;import org.example.exception.BusinessException;
import org.example.exception.SystemException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;//异常拦截器
@RestControllerAdvice
public class ProjectExceptionAdvice {@ExceptionHandler(BusinessException.class)public Result doBusinessException(BusinessException e){return new Result(e.getCode(),null,e.getMessage());}@ExceptionHandler(SystemException.class)public Result doSystemException(SystemException e){//记录日志(错误堆栈)//发送邮件给开发人员//发送短信给运维人员return new Result(e.getCode(),null,e.getMessage());}//定义处理是哪种异常@ExceptionHandler(Exception.class)public Result doException(Exception e){//记录日志(错误堆栈)//发送邮件给开发人员//发送短信给运维人员return new Result(Code.SYSTEM_UNKNOW_ERR,null,"系统繁忙,请联系管理员");}
}

6.自定义异常类

1.业务处理异常类(自定义)

package org.example.exception;public class BusinessException extends RuntimeException{private Integer code;public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public BusinessException(Integer code, String message) {super(message);this.code = code;}public BusinessException(Integer code,String message, Throwable cause) {super(message, cause);this.code = code;}
}

2.系统异常类(自定义)

package org.example.exception;public class SystemException extends RuntimeException{private Integer code;public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public SystemException(Integer code, String message) {super(message);this.code = code;}public SystemException(Integer code,String message, Throwable cause) {super(message, cause);this.code = code;}}

7.前端页面

<!DOCTYPE html><html><head><!-- 页面meta --><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><title>SpringMVC案例</title><meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport"><!-- 引入样式 --><link rel="stylesheet" href="../plugins/elementui/index.css"><link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css"><link rel="stylesheet" href="../css/style.css"></head><body class="hold-transition"><div id="app"><div class="content-header"><h1>图书管理</h1></div><div class="app-container"><div class="box"><div class="filter-container"><el-input placeholder="图书名称" v-model="pagination.queryString" style="width: 200px;"class="filter-item"></el-input><el-button @click="getAll()" class="dalfBut">查询</el-button><el-button type="primary" class="butT" @click="handleCreate()">新建</el-button></div><el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row><el-table-column type="index" align="center" label="序号"></el-table-column><el-table-column prop="type" label="图书类别" align="center"></el-table-column><el-table-column prop="name" label="图书名称" align="center"></el-table-column><el-table-column prop="description" label="描述" align="center"></el-table-column><el-table-column label="操作" align="center"><template slot-scope="scope"><el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button><el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button></template></el-table-column></el-table><!-- 新增标签弹层 --><div class="add-form"><el-dialog title="新增图书" :visible.sync="dialogFormVisible"><el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right"label-width="100px"><el-row><el-col :span="12"><el-form-item label="图书类别" prop="type"><el-input v-model="formData.type"/></el-form-item></el-col><el-col :span="12"><el-form-item label="图书名称" prop="name"><el-input v-model="formData.name"/></el-form-item></el-col></el-row><el-row><el-col :span="24"><el-form-item label="描述"><el-input v-model="formData.description" type="textarea"></el-input></el-form-item></el-col></el-row></el-form><div slot="footer" class="dialog-footer"><el-button @click="dialogFormVisible = false">取消</el-button><el-button type="primary" @click="handleAdd()">确定</el-button></div></el-dialog></div><!-- 编辑标签弹层 --><div class="add-form"><el-dialog title="编辑检查项" :visible.sync="dialogFormVisible4Edit"><el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right"label-width="100px"><el-row><el-col :span="12"><el-form-item label="图书类别" prop="type"><el-input v-model="formData.type"/></el-form-item></el-col><el-col :span="12"><el-form-item label="图书名称" prop="name"><el-input v-model="formData.name"/></el-form-item></el-col></el-row><el-row><el-col :span="24"><el-form-item label="描述"><el-input v-model="formData.description" type="textarea"></el-input></el-form-item></el-col></el-row></el-form><div slot="footer" class="dialog-footer"><el-button @click="dialogFormVisible4Edit = false">取消</el-button><el-button type="primary" @click="handleEdit()">确定</el-button></div></el-dialog></div></div></div></div></body><!-- 引入组件库 --><script src="../js/vue.js"></script><script src="../plugins/elementui/index.js"></script><script type="text/javascript" src="../js/jquery.min.js"></script><script src="../js/axios-0.18.0.js"></script><script>var vue = new Vue({el: '#app',data: {pagination: {},dataList: [],//当前页要展示的列表数据formData: {},//表单数据dialogFormVisible: false,//控制表单是否可见dialogFormVisible4Edit: false,//编辑表单是否可见rules: {//校验规则type: [{required: true, message: '图书类别为必填项', trigger: 'blur'}],name: [{required: true, message: '图书名称为必填项', trigger: 'blur'}]}},//钩子函数,VUE对象初始化完成后自动执行created() {this.getAll();},methods: {//列表getAll() {axios.get("/books").then((res) => {this.dataList = res.data.data;})},//弹出添加窗口handleCreate() {this.dialogFormVisible = true;this.formData = {}},//重置表单resetForm() {this.formData = {}},//添加handleAdd() {axios.post("/books", this.formData).then((res) => {console.log(res.data);if (res.data.code == 20011) {this.dialogFormVisible = false;this.$message.success("添加成功");} else if (res.data.code == 20010) {this.dialogFormVisible = false;this.$message.error("添加失败");} else {this.$message.error(res.data.msg);}}).finally(() => {this.getAll();})},//弹出编辑窗口handleUpdate(row) {console.log(row);//根据id查询数据axios.get("/books/" + row.id).then((res) => {if (res.data.code == 20041) {this.formData = res.data.data;this.dialogFormVisible4Edit = true;} else {this.$message.error(res.data.msg);}})//展示弹层},//编辑handleEdit() {axios.put("/books", this.formData).then((res) => {console.log(res.data);if (res.data.code == 20031) {this.dialogFormVisible4Edit = false;this.$message.success("修改成功");} else if (res.data.code == 20030) {this.dialogFormVisible4Edit = false;this.$message.error("修改失败");} else {this.$message.error(res.data.msg);}}).finally(() => {this.getAll();})},// 删除handleDelete(row) {//1.弹出提示框this.$confirm("此操作永久删除当前数据,是否继续?", "提示:", {type: 'info'}).then(() => {//2.做删除业务axios.delete("/books/" + row.id).then((res) => {if (res.data.code == 20021) {this.$message.success("删除成功");} else {this.$message.error("删除失败");}}).finally(() => {this.getAll();})}).catch(() => {//3.取消删除this.$message.info("取消删除操作");})}}})</script></html>

其余在资料中即可查找

8.业务层端口单元测试类

package org.example.service;import org.example.config.SpringConfig;
import org.example.domain.Book;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class BookServiceTest {@Autowiredprivate BookService bookService;@Testpublic void testGetById(){Book book = bookService.getById(1);System.out.println(book);}@Testpublic void testGetAll(){List<Book> all = bookService.getAll();System.out.println(all);}
}

总结

参考视频

项目地址(完整项目已打包)
码云地址
CSDN地址