Springboot整合MyBatis以及MyBatis-plus
发布日期:2021-05-07 13:38:51 浏览次数:21 分类:精选文章

本文共 2318 字,大约阅读时间需要 7 分钟。

在创建Spring Boot项目时,勾选spring webmybatis frameworkmysql 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,字段包括iddepartmentName。使用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}

编写控制器类:

@RestController
public 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;
@Configuration
public 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数据访问层,并验证了各功能的正确性。

上一篇:SpringBoot事件监听机制
下一篇:SpringBoot采用Druid数据源连接

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2025年04月11日 07时00分49秒