Spring SSM整合

news/2024/5/14 8:05:35

Spring    SpringMvc  Mybatis 整合

一. 配置类

1.1、 Spring配置类

@Configuration
@ComponentScan({"com.itheima.service"})
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class, MybatisConfig.class})
@EnableTransactionManagement
public class SpringConfig {}
  • @EnableTransactionManagement开启事务

1.2、SpringMvcConfig配置类

@Configuration
@ComponentScan("com.itheima.controller")
@EnableWebMvc
public class SpringMvcConfig {
}

1.3. ServletConfig配置类

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[]{"/"};}// 乱码处理@Overrideprotected Filter[] getServletFilters() {CharacterEncodingFilter filter = new CharacterEncodingFilter();filter.setEncoding("UTF-8");return new Filter[]{filter};}
}

1.4. JdbcConfig配置类

public class JdbcConfig {@Value("${jdbc.driver}")private String driver;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Beanpublic DataSource dataSource(){DruidDataSource dataSource = new DruidDataSource();dataSource.setDriverClassName(driver);dataSource.setUrl(url);dataSource.setUsername(username);dataSource.setPassword(password);return dataSource;}@Beanpublic PlatformTransactionManager transactionManager(DataSource dataSource){DataSourceTransactionManager ds = new DataSourceTransactionManager();ds.setDataSource(dataSource);return ds;}
}
  • 配置类内方法需要 使用@Bean注解, 注入到Spring中

1.5、Mybatis配置类 

public class MybatisConfig {@Beanpublic SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();factoryBean.setDataSource(dataSource);factoryBean.setTypeAliasesPackage("com.itheima.domain");return factoryBean;}@Beanpublic MapperScannerConfigurer mapperScannerConfigurer(){MapperScannerConfigurer msc = new MapperScannerConfigurer();msc.setBasePackage("com.itheima.dao");return msc;}}
  • 这里需要设置domain 和dao 层

1.6、jdbc配置文件  jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/spring_db
jdbc.username=root
jdbc.password=mima1234

二、业务层

2.1、domain层

public class Book {private Integer id;private String type;private String name;private String description;@Overridepublic String toString() {return "Book{" +"id=" + id +", type='" + type + '\'' +", name='" + name + '\'' +", description='" + description + '\'' +'}';}public Integer getId() {return id;}public void setId(Integer 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;}
}

2.2、Dao层

public interface BookDao {//@Insert("insert into tbl_book values(null, #{type}, #{name}, #{description})")// 占位符表示的是book中的属性名@Insert("insert into tbl_book(type, name, description) values(#{type}, #{name}, #{description})")public void save(Book book);@Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")public void update(Book book);@Delete("delete from tbl_book where id = #{id}")public void delete(Integer id);@Select("select * from tbl_book where id = #{id}")public Book getById(Integer id);@Select("select * from tbl_book")public List<Book> getAll();
}

2.3、Service接口和实现类

@Transactional
public interface BookService {/*** 保存* @param book* @return*/public boolean save(Book book);/*** 修改* @param book* @return*/public boolean update(Book book);/*** 根据ID删除* @param id* @return*/public boolean delete(Integer id);/*** 根据ID查询* @param id* @return*/public Book getById(Integer id);/*** 查询全部* @return*/public List<Book> getAll();}@Service
public class BookServiceImpl implements BookService {@Autowiredprivate BookDao bookDao;public boolean save(Book book) {bookDao.save(book);return true;}public boolean update(Book book) {bookDao.update(book);return true;}public boolean delete(Integer id) {bookDao.delete(id);return false;}public Book getById(Integer id) {return  bookDao.getById(id);}public List<Book> getAll() {return bookDao.getAll();}
}

2.4、控制器类

@RestController
@RequestMapping("/books")
public class BookController {@Autowiredprivate BookService bookService;@PostMappingpublic boolean save(@RequestBody Book book) {return bookService.save(book);}@PutMappingpublic boolean update(@RequestBody Book book) {return  bookService.update(book);}@DeleteMapping("/{id}")public boolean delete(@PathVariable Integer id) {return  bookService.delete(id);}@GetMapping("/{id}")public Book getById(@PathVariable Integer id) {return  bookService.getById(id);}@GetMappingpublic List<Book> getAll() {return bookService.getAll();}
}

三、封装返回值

3.1、Code类

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;
}

3.2、Result类

public class Result {private Object data;private Integer code;private  String msg;public Result() {}public Result( Integer code,Object data, String msg) {this.data = data;this.code = code;this.msg = msg;}public Result(Integer code,Object data) {this.data = data;this.code = code;}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;}
}

3.3、把控制器返回类型改成Result

@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);}
}

四、异常

4.1、异常类

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;}}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;}}

4.2、异常AOP

@RestControllerAdvice
public class ProjectExceptionAdvice  {@ExceptionHandler(SystemException.class)public Result doSystemException(SystemException ex){// 记录日志// 发送消息给运维// 发送邮件给开发人员return  new Result(ex.getCode(), null, ex.getMessage());}@ExceptionHandler(BusinessException.class)public Result doBusinessException(BusinessException ex){return new Result(ex.getCode(), null, ex.getMessage());}// 处理其他异常@ExceptionHandler(Exception.class)public Result doException(Exception ex){// 记录日志// 发送消息给运维// 发送邮件给开发人员return new Result(Code.SYSTEM_UNKNOWN_ERR, null, "系统繁忙请稍后重试!!!");}
}
  • @RestControllerAdvice 注解声明为AOP类 后,会自动注入到Spring内

4.3、异常使用

public Book getById(Integer id) {if( id == 1){throw new BusinessException(Code.BUSINESS_ERR, "请输入正确的年龄");}try {int i = 1 / 0;}catch (Exception e){throw new SystemException(Code.SYSTEM_ERR, "服务器异常", e);}return  bookDao.getById(id);
}
  •  根据情况抛出不同异常


http://www.mrgr.cn/p/74487547

相关文章

会议OA系统会议管理模块开发思路(layui搭建)

目录 一.为什么要进行开发 1.开发目的 2.项目流程 A.发起会议请求过程 1.首先实现我们的多选下拉框功能&#xff01; 2.时间组件功能&#xff0c;并且提交我们新增加的会议内容 3.在进行发起会议编码时遇到的问题&#xff0c;BUG 3.1.有点时候js访问不到路径 3.2在增加…

linux下docker安装、镜像下载、镜像基础操作、容器基础操作

目录 一、环境准备 1、开启虚拟化 2、关闭防火墙 3、yum仓库获取阿里源&#xff08;清华、京东都可以&#xff09; 4、确保能ping到外网 二、安装docker 1、yum安装docker 2、启动docker并设置开机自启 3、安装docker-ce阿里镜像加速器 三、docker基本操作 1、查看版…

FileHub使用教程:Github Token获取步骤,使用快人一步

FileHub介绍 filehub是我开发的一个免费文件存储软件&#xff0c;可存万物。软件仓库&#xff1a;GitHub - Sjj1024/s-hub: 一个使用github作为资源存储的软件 软件下载地址&#xff1a;。有问题可以留言或者提Issue&#xff0c; 使用第一步&#xff1a;获取Github Token 使…

【字节跳动青训营】后端笔记整理-3 | Go语言工程实践之测试

**本文由博主本人整理自第六届字节跳动青训营&#xff08;后端组&#xff09;&#xff0c;首发于稀土掘金&#xff1a;&#x1f517;Go语言工程实践之测试 | 青训营 目录 一、概述 1、回归测试 2、集成测试 3、单元测试 二、单元测试 1、流程 2、规则 3、单元测试的例…

卷积神经网络识别人脸项目—使用百度飞桨ai计算

卷积神经网络识别人脸项目的详细过程 整个项目需要的准备文件&#xff1a; 下载链接&#xff1a; 链接&#xff1a;https://pan.baidu.com/s/1WEndfi14EhVh-8Vvt62I_w 提取码&#xff1a;7777 链接&#xff1a;https://pan.baidu.com/s/10weqx3r_zbS5gNEq-xGrzg 提取码&#x…

Transformer 论文学习笔记

重新学习了一下&#xff0c;整理了一下笔记 论文&#xff1a;《Attention Is All You Need》 代码&#xff1a;http://nlp.seas.harvard.edu/annotated-transformer/ 地址&#xff1a;https://arxiv.org/abs/1706.03762v5 翻译&#xff1a;Transformer论文翻译 特点&#xff1…

网络面试合集

传输层的数据结构是什么&#xff1f; 就是在问他的协议格式&#xff1a;UDP&TCP 2.1.1三次握手 通信前&#xff0c;要先建立连接&#xff0c;确保双方都是在线&#xff0c;具有数据收发的能力。 2.1.2四次挥手 通信结束后&#xff0c;会有一个断开连接的过程&#xff0…

二十、像素流送,软件即游戏,SaaG时代到来

有了像素流送插件,就可以在远程计算机上运行虚幻引擎应用,并将其渲染效果和音频流送到任意平台的现代网页浏览器上。此外,还可以在浏览器上与流互动,遥控虚幻引擎应用。 1、启用像素流插件 虚幻编辑器的主菜单中选择 编辑(Edit) > 插件(Plugins),在图像(Graph…

selenium-web自动化测试

一、selenium环境部署 1.准备chrome浏览器&#xff08;其他浏览器也行&#xff09; 2.准备chrome驱动包 步骤一&#xff1a;查看自己的谷歌浏览器版本(浏览器版本和驱动版本一定要对应) 步骤二&#xff1a;下载对应的驱动包, 下载路径 : ChromeDriver - WebDriver for Chrom…

DragGAN:用崭新的方式进行图像处理

该项目的论文被SIGGRAPH 2023 收录&#xff0c;论文以 StyleGAN2 架构为基础&#xff0c;实现了 “Drag” 关键点就能轻松 P 图的效果。 https://github.com/XingangPan/DragGAN https://vcai.mpi-inf.mpg.de/projects/DragGAN/ 目录 原图1测试一测试二测试三 原图2测试一测试…

【数据结构与算法】基数排序

基数排序 基数排序&#xff08;Radix Sort&#xff09;属于“分配式排序”&#xff0c;又称“桶子法”或 bin sort&#xff0c;顾名思义&#xff0c;它是通过键值的各个位的值&#xff0c;将要排序的元素分配至某些“桶”中&#xff0c;达到排序的作用。基数排序法是属于稳定性…

【文献分享】比目前最先进的模型轻30%!高效多机器人SLAM蒸馏描述符!

论文题目&#xff1a;Descriptor Distillation for Efficient Multi-Robot SLAM 中文题目&#xff1a;高效多机器人SLAM蒸馏描述符 作者&#xff1a;Xiyue Guo, Junjie Hu, Hujun Bao and Guofeng Zhang 作者机构&#xff1a;浙江大学CAD&CG国家重点实验室 香港中文大学…

51单片机——串行口通信

目录 1、51单片机串口通信介绍 2、串行口相关寄存器 2.1 、串行口控制寄存器SCON和PCON 2.1.1 SCON&#xff1a;串行控制寄存器 (可位寻址) 2.1.2 PCON&#xff1a;电源控制寄存器&#xff08;不可位寻址&#xff09; 2.2、串行口数据缓冲寄存器SBUF 2.3、从机地址控制…

持续贡献开源力量,棱镜七彩加入openKylin

近日&#xff0c;棱镜七彩签署 openKylin 社区 CLA&#xff08;Contributor License Agreement 贡献者许可协议&#xff09;&#xff0c;正式加入openKylin 开源社区。 棱镜七彩成立于2016年&#xff0c;是一家专注于开源安全、软件供应链安全的创新型科技企业。自成立以来&…

如何有效地使用ChatGPT写小说讲故事?

​构思故事情节&#xff0c;虽有趣但耗时&#xff0c;容易陷入写作瓶颈。ChatGPT可提供灵感&#xff0c;帮你解决写作难题。要写出引人入胜的故事&#xff0c;关键在于抓住八个要素——主题、人物、视角、背景、情节、语气、冲突和解决办法。 直接给出故事模板&#xff0c;你可…

Selenium+Java环境搭建(测试系列6)

目录 前言&#xff1a; 1.浏览器 1.1下载Chrome浏览器 1.2查看Chrome浏览器版本 1.3下载Chrome浏览器的驱动 2.配置系统环境变量path 3.验证是否成功 4.出现的问题 结束语&#xff1a; 前言&#xff1a; 这节中小编给大家讲解一下有关于Selenium Java环境的搭建&…

C语言指针进阶-1

本篇文章带来 1. 字符指针 2. 数组指针 3. 指针数组的相关知识详细讲解&#xff01; 如果您觉得文章不错&#xff0c;期待你的一键三连哦&#xff0c;你的鼓励是我创作的动力之源&#xff0c;让我们一起加油&#xff0c;一起奔跑&#xff0c;让我们顶峰相见&#xff01;&#…

智慧农业:科技赋能农村发展

智慧农业发展前景灿烂多彩&#xff0c;正为农业带来新的转型升级。随着科技的不断发展&#xff0c;数字化、自动化和智能化技术逐渐渗透进农业领域&#xff0c;为农民提供了更多高效便捷的农业管理方式。智慧农业通过物联网、大数据、人工智能等先进技术&#xff0c;实现对农田…

前端小练-仿掘金导航栏

文章目录 前言项目结构导航实现创作中心移动小球消息提示 完整代码 前言 闲的&#xff0c;你信嘛&#xff0c;还得开发一个基本的门户社区网站&#xff0c;来给到Hlang,不然我怕说工作量不够。那么这个的话&#xff0c;其实也很好办&#xff0c;主要是这个门户网站的UI写起来麻…

【深度学习】以图搜索- 2021sota repVgg来抽取向量 + facebook的faiss的做特征检索, 从环境搭建到运行案例从0到1

文章目录 前言安装小试牛刀用repVgg抽取向量构建Faiss索引进行相似性搜索本项目延伸其它项目拓展总结 前言 Faiss的全称是Facebook AI Similarity Search。 这是一个开源库&#xff0c;针对高维空间中的海量数据&#xff0c;提供了高效且可靠的检索方法。 暴力检索耗时巨大&a…