
Springboot整合MyBatis以及MyBatis-plus
发布日期:2021-05-07 13:38:51
浏览次数:21
分类:精选文章
本文共 2318 字,大约阅读时间需要 7 分钟。
在创建Spring Boot项目时,勾选spring web
、mybatis framework
、mysql driver
等相关插件。完成项目创建后,配置数据库连接信息到application.yml
文件中。
数据库连接配置示例:
spring: datasource: username: root password: root url: jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver
创建数据库表department
,字段包括id
、departmentName
。使用SQL执行以下命令:
CREATE TABLE department ( id INT PRIMARY KEY AUTO_INCREMENT, departmentName VARCHAR(255) NOT NULL);
编写MyBatis Mapper接口,使用XML配置来定义SQL语句:
delete from department where id=#{id} insert into department(departmentName) values("#{departmentName}") update department set departmentName=#{departmentName} where id=#{id}
编写控制器类:
@RestControllerpublic class DeptController { @Autowired private DepartmentMapper departmentMapper; @GetMapping("/dept/{id}") public Department getDepartment(@PathVariable Integer id) { return departmentMapper.getDeptById(id); } @GetMapping("/dept") public Department insertDepartment(@RequestBody Department department) { return departmentMapper.insertDept(department); }}
测试控制器端点,确保接口正常响应。配置MyBatis核心配置文件mybatis-config.xml
:
在application.yml
中添加MyBatis配置:
mybatis: config-location: classpath:mybatis/mybatis-config.xml mapper-locations: classpath:mybatis/mapper/*.xml
为了启用分页功能,添加分页拦截器:
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class MyBatisConfig { @Bean public MybatisPlusInterceptor paginationInterceptor() { PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(); paginationInnerInterceptor.setOverflow(true); paginationInnerInterceptor.setMaxLimit(500L); MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(paginationInnerInterceptor); return interceptor; }}
通过以上步骤,成功配置了Spring Boot项目的MyBatis数据访问层,并验证了各功能的正确性。
发表评论
最新留言
能坚持,总会有不一样的收获!
[***.219.124.196]2025年04月11日 07时00分49秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
聊聊我的五一小假期
2019-03-05
面向对象之异常处理:多路捕获
2019-03-05
Vue新建项目——页面初始化
2019-03-05
Node.js包使用系列(一)——修改NPM全局下载和缓存路径
2019-03-05
TDengine使用(一)——TDengine下载与安装
2019-03-05
6.14编一个程序,将两个字符串s1和s2比较,不要用strcmp函数。
2019-03-05
Java纯文本文件显示工具制作
2019-03-05
Unity2D Fixed Joint 2D详解
2019-03-05
三、案例:留言板 & url.parse()
2019-03-05
Python实验26:计算文件MD5值
2019-03-05
LeetCode:28. 实现 strStr()——————简单
2019-03-05
LeetCode:697. 数组的度————简单
2019-03-05
LeetCode:1052. 爱生气的书店老板————中等
2019-03-05
C语言的6大基本数据类型!(学习C语言小白必备!!)
2019-03-05
Nginx配置反向代理与负载均衡
2019-03-05
Lionheart万汇:布林线双底形态分析技巧
2019-03-05
LHCM万汇:在需求上升中,美国贸易赤字创下历史新高
2019-03-05
Mybatis的入门01
2019-03-05
Vue路由嵌套刷新后页面没有重新渲染
2019-03-05