文章目录
前言
为了巩固所学的知识,作者尝试着开始发布一些学习笔记类的博客,方便日后回顾。当然,如果能帮到一些萌新进行新技术的学习那也是极好的。作者菜菜一枚,文章中如果有记录错误,欢迎读者朋友们批评指正。
(博客的参考源码可以在我主页的资源里找到,如果在学习的过程中有什么疑问欢迎大家在评论区向我提出)
建议先去浏览本人ssm专栏发布的ssm快速入门案例(一)(二)后再阅读本文章
四、基于SpringBoot的SSM整合案例
1.设计创建数据库表tbl_book
--------------------------------Table structure for tbl_book
------------------------------
DROP TABLE IF EXISTS `tbl_book`;
CREATE TABLE `tbl_book` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`description` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,PRIMARY KEY (`id`)USING BTREE
) ENGINE =InnoDB AUTO_INCREMENT =13CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT =Dynamic;--------------------------------Records of tbl_book
------------------------------
INSERT INTO `tbl_book` VALUES (1,'计算机理论', 'Spring实战 第5版', 'Spring入门经典教程,深入理解Spring原理技术内幕');
INSERT INTO `tbl_book` VALUES (2,'计算机理论', 'Spring5核心原理与30个类手写实战', '十年沉淀之作,手写Spring精华思想');
INSERT INTO `tbl_book` VALUES (3,'计算机理论', 'Spring5 设计模式', '深入Spring源码剖析Spring源码中蕴含的10大设计模式');
INSERT INTO `tbl_book` VALUES (4,'计算机理论', 'Spring MVC+MyBatis开发从入门到项目实战', '全方位解析面向Web应用的轻量级框架,带你成为Spring MVC开发高手');
INSERT INTO `tbl_book` VALUES (5,'计算机理论', '轻量级JavaWeb企业应用实战', '源码级剖析Spring框架,适合已掌握Java基础的读者');
INSERT INTO `tbl_book` VALUES (6,'计算机理论', 'Java核心技术 卷I 基础知识(原书第11版)', 'CoreJava 第11版,Jolt大奖获奖作品,针对Java SE9、10、11全面更新');
INSERT INTO `tbl_book` VALUES (7,'计算机理论', '深入理解Java虚拟机', '5个维度全面剖析JVM,大厂面试知识点全覆盖');
INSERT INTO `tbl_book` VALUES (8,'计算机理论', 'Java编程思想(第4版)', 'Java学习必读经典,殿堂级著作!赢得了全球程序员的广泛赞誉');
INSERT INTO `tbl_book` VALUES (9,'计算机理论', '零基础学Java(全彩版)', '零基础自学编程的入门图书,由浅入深,详解Java语言的编程思想和核心技术');
INSERT INTO `tbl_book` VALUES (10,'市场营销', '直播就该这么做:主播高效沟通实战指南', '李子柒、李佳琦、薇娅成长为网红的秘密都在书中');
INSERT INTO `tbl_book` VALUES (11,'市场营销', '直播销讲实战一本通', '和秋叶一起学系列网络营销书籍');
INSERT INTO `tbl_book` VALUES (12,'市场营销', '直播带货:淘宝、天猫直播从新手到高手', '一本教你如何玩转直播的书,10堂课轻松实现带货月入3W+');
2.创建新的SpringBoot模块,勾选相关依赖
3. 添加SpringBoot创建项目时没有提供的相关坐标
<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.16</version></dependency>
4.根据数据库表创建实体类Book
publicclassBook{//此处省略gettr、setter和toString方法privateInteger id;privateString type;privateString name;privateString description;
5.编写dao层操作BookDao
@MapperpublicinterfaceBookDao{@Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")publicintsave(Book book);@Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")publicintupdate(Book book);@Delete("delete from tbl_book where id = #{id}")publicintdelete(Integer id);@Select("select * from tbl_book where id = #{id}")publicBookgetById(Integer id);@Select("select * from tbl_book")publicList<Book>getAll();}
6.编写Service服务层接口BookService
@TransactionalpublicinterfaceBookService{/**
* 保存
* @param book
* @return
*/publicbooleansave(Book book);/**
* 修改
* @param book
* @return
*/publicbooleanupdate(Book book);/**
* 按id删除
* @param id
* @return
*/publicbooleandelete(Integer id);/**
* 按id查询
* @param id
* @return
*/publicBookgetById(Integer id);/**
* 查询全部
* @return
*/publicList<Book>getAll();}
7.编写服务层实现类BookServiceImpl
@ServicepublicclassBookServiceImplimplementsBookService{@AutowiredprivateBookDao bookDao;publicbooleansave(Book book){return bookDao.save(book)>0;}publicbooleanupdate(Book book){return bookDao.update(book)>0;}publicbooleandelete(Integer id){return bookDao.delete(id)>0;}publicBookgetById(Integer id){if(id ==1){thrownewBusinessException(Code.BUSINESS_ERR,"请不要使用你的技术挑战我的耐性!");}// //将可能出现的异常进行包装,转换成自定义异常// try{// int i = 1/0;// }catch (Exception e){// throw new SystemException(Code.SYSTEM_TIMEOUT_ERR,"服务器访问超时,请重试!",e);// }return bookDao.getById(id);}publicList<Book>getAll(){return bookDao.getAll();}}
8.编写Book模块Controller层BookController
@RestController@RequestMapping("/books")publicclassBookController{@AutowiredprivateBookService bookService;@PostMappingpublicResultsave(@RequestBodyBook book){boolean flag = bookService.save(book);returnnewResult(flag ?Code.SAVE_OK:Code.SAVE_ERR,flag);}@PutMappingpublicResultupdate(@RequestBodyBook book){boolean flag = bookService.update(book);returnnewResult(flag ?Code.UPDATE_OK:Code.UPDATE_ERR,flag);}@DeleteMapping("/{id}")publicResultdelete(@PathVariableInteger id){boolean flag = bookService.delete(id);returnnewResult(flag ?Code.DELETE_OK:Code.DELETE_ERR,flag);}@GetMapping("/{id}")publicResultgetById(@PathVariableInteger id){Book book = bookService.getById(id);Integer code = book !=null?Code.GET_OK :Code.GET_ERR;String msg = book !=null?"":"数据查询失败,请重试!";returnnewResult(code,book,msg);}@GetMappingpublicResultgetAll(){List<Book> bookList = bookService.getAll();Integer code = bookList !=null?Code.GET_OK :Code.GET_ERR;String msg = bookList !=null?"":"数据查询失败,请重试!";returnnewResult(code,bookList,msg);}}
9.状态码类相关设计
- Code类
packageorg.example.controller;publicclassCode{publicstaticfinalInteger SAVE_OK =20011;publicstaticfinalInteger DELETE_OK =20021;publicstaticfinalInteger UPDATE_OK =20031;publicstaticfinalInteger GET_OK =20041;publicstaticfinalInteger SAVE_ERR =20010;publicstaticfinalInteger DELETE_ERR =20020;publicstaticfinalInteger UPDATE_ERR =20030;publicstaticfinalInteger GET_ERR =20040;publicstaticfinalInteger SYSTEM_ERR =50001;publicstaticfinalInteger SYSTEM_TIMEOUT_ERR =50002;publicstaticfinalInteger SYSTEM_UNKNOW_ERR =59999;publicstaticfinalInteger BUSINESS_ERR =60002;}
- ProjectExceptionAdvice类
@RestControllerAdvicepublicclassProjectExceptionAdvice{@ExceptionHandler(SystemException.class)publicResultdoSystemException(SystemException ex){//记录日志//发送消息给运维//发送邮件给开发人员,ex对象发送给开发人员returnnewResult(ex.getCode(),null,ex.getMessage());}@ExceptionHandler(BusinessException.class)publicResultdoBusinessException(BusinessException ex){returnnewResult(ex.getCode(),null,ex.getMessage());}@ExceptionHandler(Exception.class)publicResultdoOtherException(Exception ex){//记录日志//发送消息给运维//发送邮件给开发人员,ex对象发送给开发人员returnnewResult(Code.SYSTEM_UNKNOW_ERR,null,"系统繁忙,请稍后再试!");}}
- Result类
publicclassResult{//此处省略getter、setter方法privateObject data;privateInteger code;privateString msg;publicResult(){}publicResult(Integer code,Object data){this.data = data;this.code = code;}publicResult(Integer code,Object data,String msg){this.data = data;this.code = code;this.msg = msg;}publicObjectgetData(){return data;}}
- BusinessException类
publicclassBusinessExceptionextendsRuntimeException{privateInteger code;publicIntegergetCode(){return code;}publicvoidsetCode(Integer code){this.code = code;}publicBusinessException(Integer code,String message){super(message);this.code = code;}publicBusinessException(Integer code,String message,Throwable cause){super(message, cause);this.code = code;}}
- SystemException类
publicclassSystemExceptionextendsRuntimeException{privateInteger code;publicIntegergetCode(){return code;}publicvoidsetCode(Integer code){this.code = code;}publicSystemException(Integer code,String message){super(message);this.code = code;}publicSystemException(Integer code,String message,Throwable cause){super(message, cause);this.code = code;}}
10.对比基于Spring的ssm整合案例
(详情可以去关注作者的ssm专栏)
总结
欢迎各位留言交流以及批评指正,如果文章对您有帮助或者觉得作者写的还不错可以点一下关注,点赞,收藏支持一下。
(博客的参考源码可以在我主页的资源里找到,如果在学习的过程中有什么疑问欢迎大家在评论区向我提出)
版权归原作者 东离与糖宝 所有, 如有侵权,请联系我们删除。