(4)在业务中添加事务管理
-
创建平台事务管理器==》实际是jdbc的事务
public class JdbcConfig {@Beanpublic PlatformTransactionManager transactionManager(DataSource ds){DataSourceTransactionManager transactionManager =new DataSourceTransactionManager();transactionManager.setDataSource(ds);return transactionManager;} }
-
开启事务管理器注解支持
@EnableTransactionManagement public class SpringConfig {}
-
在接口上开启事务管理
@Transactional public interface BookService {...}
(5)封装表现层数据
-
前端接收数据格式==》创建结果模型类
-
封装数据到data中
-
封装操作结果到code中==》不同code对应不同操作结果
-
封装特殊消息到message(msg)属性中
-
期待格式
-
-
设置统一数据返回结果类
public class Result {private Object data;private Integer code;private String msg;setter、getter... }
-
该结果类的成员属性不固定,根据需求添加
-
该结果类的构造方法书写多个,方便返回灵活的数据
-
封装对应的code编码==》不是标准,前后端协议沟通一致即可
public class Code {public static final Integer SAVE_OK = 20011;//新增成功public static final Integer SAVE_ERR = 20010;//新增失败public static final Integer DELETE_OK = 20021;//删除成功public static final Integer DELETE_ERR = 20020;//删除失败public static final Integer UPDATE_OK = 20031;//更新成功public static final Integer UPDATE_ERR = 20030;//更新失败public static final Integer GET_OK = 20041;//查询成功public static final Integer GET_ERR = 20040;//查询失败 }
-
将表现层返回数据类型统一为Result类
@PostMapping public Result save(@RequestBody Book book) {System.out.println("save...");Boolean status = bookService.saveBook(book);System.out.println("save...");return new Result(status ? Code.SAVE_OK : Code.SAVE_ERR, status); } @DeleteMapping("/{id}")public Result delete(@PathVariable Integer id) {Boolean status = bookService.deleteBook(id);return new Result(status ? Code.DELETE_OK : Code.DELETE_ERR, status); } @PutMapping public Result update(@RequestBody Book book) {Boolean status = bookService.updateBook(book);return new Result(status ? Code.UPDATE_OK : Code.UPDATE_ERR, status); } @GetMapping public Result getAllBook() {List<Book> books = bookService.selectAllBook();Integer code = books != null ? Code.GET_OK : Code.GET_ERR;String msg = books != null ? "" : "查询失败,请重试!";return new Result(code,books,msg); } @GetMapping("/{id}") public Result getBookById(@PathVariable Integer id) {Book book = bookService.selectBookById(id);Integer code = book != null ? Code.GET_OK : Code.GET_ERR;String msg = book != null ? "" : "查询失败,请重试!";return new Result(code,book,msg); }