Spring Boot 3与MyBatis整合:从零实现增删改查全流程指南

一、项目初始化与基础配置

1.1 创建Spring Boot 3项目

通过主流IDE(如IntelliJ IDEA或Eclipse)的Spring Initializr插件快速生成项目骨架,需注意以下关键配置:

  • 基础依赖:选择Spring Web、MyBatis Framework、MySQL Driver等核心组件
  • JDK版本:确保使用JDK 17或更高版本(Spring Boot 3最低要求)
  • 构建工具:推荐使用Maven进行依赖管理,项目结构需符合Maven标准目录规范

1.2 配置文件优化

将默认的application.properties转换为YAML格式的application.yml,实现更清晰的层级配置:

  1. server:
  2. port: 8080
  3. spring:
  4. datasource:
  5. url: jdbc:mysql://localhost:3306/demo_db
  6. username: root
  7. password: '012345' # 密码以0开头需加引号
  8. driver-class-name: com.mysql.cj.jdbc.Driver
  9. mybatis:
  10. mapper-locations: classpath:mapper/*.xml
  11. type-aliases-package: com.example.demo.entity

关键说明

  • 数据库密码若以数字0开头,必须使用单引号包裹避免自动截断
  • 通过mapper-locations指定MyBatis映射文件存放路径
  • 使用type-aliases-package简化实体类全限定名引用

1.3 依赖管理优化

pom.xml中添加必要依赖时,建议使用版本管理属性避免硬编码:

  1. <properties>
  2. <java.version>17</java.version>
  3. <mybatis-spring-boot.version>3.0.3</mybatis-spring-boot.version>
  4. </properties>
  5. <dependencies>
  6. <!-- Spring Boot Starter -->
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-web</artifactId>
  10. </dependency>
  11. <!-- MyBatis集成 -->
  12. <dependency>
  13. <groupId>org.mybatis.spring.boot</groupId>
  14. <artifactId>mybatis-spring-boot-starter</artifactId>
  15. <version>${mybatis-spring-boot.version}</version>
  16. </dependency>
  17. <!-- MySQL驱动 -->
  18. <dependency>
  19. <groupId>com.mysql</groupId>
  20. <artifactId>mysql-connector-j</artifactId>
  21. <scope>runtime</scope>
  22. </dependency>
  23. </dependencies>

二、数据库集成方案

2.1 数据库表设计

以用户管理模块为例,创建基础表结构:

  1. CREATE TABLE `user` (
  2. `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  3. `username` varchar(50) NOT NULL COMMENT '用户名',
  4. `email` varchar(100) DEFAULT NULL COMMENT '电子邮箱',
  5. `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  6. `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  7. PRIMARY KEY (`id`),
  8. UNIQUE KEY `idx_username` (`username`)
  9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户信息表';

2.2 实体类开发

遵循JavaBean规范创建实体类,推荐使用Lombok简化代码:

  1. @Data
  2. @NoArgsConstructor
  3. @AllArgsConstructor
  4. @TableName("user") // 若使用通用Mapper可添加此注解
  5. public class User {
  6. @TableId(type = IdType.AUTO) // 主键自增策略
  7. private Long id;
  8. @NotBlank(message = "用户名不能为空")
  9. private String username;
  10. @Email(message = "邮箱格式不正确")
  11. private String email;
  12. private LocalDateTime createTime;
  13. private LocalDateTime updateTime;
  14. }

2.3 MyBatis映射配置

采用XML映射文件方式实现SQL管理:

  1. <!-- UserMapper.xml -->
  2. <mapper namespace="com.example.demo.mapper.UserMapper">
  3. <resultMap id="BaseResultMap" type="User">
  4. <id column="id" property="id"/>
  5. <result column="username" property="username"/>
  6. <result column="email" property="email"/>
  7. <result column="create_time" property="createTime"/>
  8. <result column="update_time" property="updateTime"/>
  9. </resultMap>
  10. <insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id">
  11. INSERT INTO user(username, email)
  12. VALUES(#{username}, #{email})
  13. </insert>
  14. <select id="selectById" resultMap="BaseResultMap">
  15. SELECT * FROM user WHERE id = #{id}
  16. </select>
  17. </mapper>

三、业务逻辑实现

3.1 Mapper接口定义

创建标准CRUD接口,推荐使用MyBatis-Plus的IService接口扩展:

  1. public interface UserMapper extends BaseMapper<User> {
  2. // 自定义复杂查询方法
  3. List<User> selectByCondition(@Param("condition") Map<String, Object> condition);
  4. }

3.2 Service层实现

  1. @Service
  2. public class UserServiceImpl implements UserService {
  3. @Autowired
  4. private UserMapper userMapper;
  5. @Override
  6. public User createUser(UserDTO userDTO) {
  7. User user = new User();
  8. BeanUtils.copyProperties(userDTO, user);
  9. userMapper.insert(user);
  10. return user;
  11. }
  12. @Override
  13. public User getUserById(Long id) {
  14. return userMapper.selectById(id);
  15. }
  16. @Override
  17. @Transactional
  18. public boolean updateUser(UserDTO userDTO) {
  19. User user = userMapper.selectById(userDTO.getId());
  20. if (user == null) {
  21. throw new RuntimeException("用户不存在");
  22. }
  23. BeanUtils.copyProperties(userDTO, user);
  24. return userMapper.updateById(user) > 0;
  25. }
  26. }

3.3 Controller层开发

  1. @RestController
  2. @RequestMapping("/api/users")
  3. public class UserController {
  4. @Autowired
  5. private UserService userService;
  6. @PostMapping
  7. public ResponseEntity<User> createUser(@Valid @RequestBody UserDTO userDTO) {
  8. User user = userService.createUser(userDTO);
  9. return ResponseEntity.created(URI.create("/api/users/" + user.getId()))
  10. .body(user);
  11. }
  12. @GetMapping("/{id}")
  13. public ResponseEntity<User> getUser(@PathVariable Long id) {
  14. return ResponseEntity.ok(userService.getUserById(id));
  15. }
  16. @PutMapping("/{id}")
  17. public ResponseEntity<Void> updateUser(@PathVariable Long id,
  18. @Valid @RequestBody UserDTO userDTO) {
  19. userDTO.setId(id);
  20. if (userService.updateUser(userDTO)) {
  21. return ResponseEntity.ok().build();
  22. }
  23. return ResponseEntity.notFound().build();
  24. }
  25. }

四、高级配置与优化

4.1 分页插件配置

添加PageHelper分页支持:

  1. @Configuration
  2. public class MyBatisConfig {
  3. @Bean
  4. public PageInterceptor pageInterceptor() {
  5. PageInterceptor interceptor = new PageInterceptor();
  6. Properties properties = new Properties();
  7. properties.setProperty("reasonable", "true");
  8. properties.setProperty("supportMethodsArguments", "true");
  9. interceptor.setProperties(properties);
  10. return interceptor;
  11. }
  12. }

4.2 动态数据源配置

针对多数据源场景,可实现AbstractRoutingDataSource:

  1. public class DynamicDataSource extends AbstractRoutingDataSource {
  2. @Override
  3. protected Object determineCurrentLookupKey() {
  4. return DataSourceContextHolder.getDataSourceType();
  5. }
  6. }
  7. // 配置类示例
  8. @Configuration
  9. public class DataSourceConfig {
  10. @Bean
  11. @ConfigurationProperties("spring.datasource.master")
  12. public DataSource masterDataSource() {
  13. return DataSourceBuilder.create().build();
  14. }
  15. @Bean
  16. public DataSource dynamicDataSource() {
  17. Map<Object, Object> targetDataSources = new HashMap<>();
  18. targetDataSources.put("master", masterDataSource());
  19. // 添加其他数据源...
  20. DynamicDataSource dynamicDataSource = new DynamicDataSource();
  21. dynamicDataSource.setTargetDataSources(targetDataSources);
  22. dynamicDataSource.setDefaultTargetDataSource(masterDataSource());
  23. return dynamicDataSource;
  24. }
  25. }

4.3 性能监控方案

集成Actuator实现MyBatis监控:

  1. management:
  2. endpoints:
  3. web:
  4. exposure:
  5. include: metrics,health,info
  6. endpoint:
  7. metrics:
  8. enabled: true

五、常见问题解决方案

5.1 启动报错处理

  • 包扫描失败:检查@MapperScan注解配置是否正确
  • 数据库连接失败:验证数据库服务状态及网络连通性
  • SQL语法错误:检查MySQL版本与驱动兼容性

5.2 事务失效场景

  • 确保事务方法为public修饰
  • 检查是否在同一个类中调用事务方法
  • 验证是否正确引入@Transactional注解

5.3 分页参数失效

  • 检查PageHelper.startPage()调用位置
  • 验证拦截器配置顺序是否正确
  • 确保SQL语句后直接获取结果集

本文通过完整的项目实践,系统阐述了Spring Boot 3与MyBatis整合开发的核心要点。从基础配置到高级特性,每个环节都提供了可落地的解决方案和最佳实践建议。开发者可基于此框架快速构建企业级应用,同时可根据实际需求灵活扩展功能模块。建议在实际开发过程中结合日志系统、单元测试等工程化实践,构建更健壮的应用体系。