Spring Boot 3与MyBatis深度整合:数据库操作全流程实战指南

一、技术选型与整合原理

在Java生态中,Spring Boot 3作为新一代微服务框架,通过自动配置机制大幅简化开发流程。MyBatis作为持久层框架,凭借其灵活的SQL映射特性,成为数据库操作的首选方案。二者整合的核心在于:

  1. 自动配置机制:Spring Boot通过spring-boot-starter-data-mybatis依赖自动注入SqlSessionFactory
  2. 注解驱动开发:使用@MapperScan实现接口扫描,替代传统XML配置
  3. 事务管理:通过@Transactional注解实现声明式事务控制

典型项目结构如下:

  1. src/
  2. ├── main/
  3. ├── java/
  4. └── com/example/
  5. ├── config/ # 配置类
  6. ├── controller/ # 控制器层
  7. ├── service/ # 业务逻辑层
  8. ├── mapper/ # 数据访问层
  9. └── entity/ # 实体类
  10. └── resources/
  11. ├── mapper/ # SQL映射文件
  12. └── application.yml # 配置文件

二、环境搭建与依赖配置

2.1 基础依赖配置

pom.xml中添加核心依赖:

  1. <dependencies>
  2. <!-- Spring Boot Starter Web -->
  3. <dependency>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-starter-web</artifactId>
  6. </dependency>
  7. <!-- MyBatis Spring Boot Starter -->
  8. <dependency>
  9. <groupId>org.mybatis.spring.boot</groupId>
  10. <artifactId>mybatis-spring-boot-starter</artifactId>
  11. <version>3.0.3</version>
  12. </dependency>
  13. <!-- 数据库驱动(以MySQL为例) -->
  14. <dependency>
  15. <groupId>com.mysql</groupId>
  16. <artifactId>mysql-connector-j</artifactId>
  17. <scope>runtime</scope>
  18. </dependency>
  19. </dependencies>

2.2 数据库配置

application.yml中配置数据源:

  1. spring:
  2. datasource:
  3. url: jdbc:mysql://localhost:3306/demo_db?useSSL=false
  4. username: root
  5. password: 123456
  6. driver-class-name: com.mysql.cj.jdbc.Driver
  7. mybatis:
  8. mapper-locations: classpath:mapper/*.xml
  9. type-aliases-package: com.example.entity
  10. configuration:
  11. map-underscore-to-camel-case: true

三、核心功能实现

3.1 实体类设计

以用户管理为例,创建User实体类:

  1. @Data
  2. public class User {
  3. private Long id;
  4. private String username;
  5. private String email;
  6. private LocalDateTime createTime;
  7. // 省略getter/setter
  8. }

3.2 Mapper接口开发

创建UserMapper接口,定义基础CRUD方法:

  1. @Mapper
  2. public interface UserMapper {
  3. @Select("SELECT * FROM user WHERE id = #{id}")
  4. User selectById(Long id);
  5. @Insert("INSERT INTO user(username, email) VALUES(#{username}, #{email})")
  6. @Options(useGeneratedKeys = true, keyProperty = "id")
  7. int insert(User user);
  8. @Update("UPDATE user SET username=#{username}, email=#{email} WHERE id=#{id}")
  9. int update(User user);
  10. @Delete("DELETE FROM user WHERE id=#{id}")
  11. int delete(Long id);
  12. }

3.3 动态SQL实现

对于复杂查询场景,使用XML映射文件实现动态SQL:

  1. <!-- UserMapper.xml -->
  2. <mapper namespace="com.example.mapper.UserMapper">
  3. <select id="selectByCondition" resultType="User">
  4. SELECT * FROM user
  5. <where>
  6. <if test="username != null">
  7. AND username LIKE CONCAT('%', #{username}, '%')
  8. </if>
  9. <if test="email != null">
  10. AND email = #{email}
  11. </if>
  12. </where>
  13. ORDER BY create_time DESC
  14. </select>
  15. </mapper>

3.4 事务管理实践

在Service层使用@Transactional注解控制事务:

  1. @Service
  2. @RequiredArgsConstructor
  3. public class UserService {
  4. private final UserMapper userMapper;
  5. @Transactional
  6. public void batchInsert(List<User> users) {
  7. users.forEach(userMapper::insert);
  8. // 若抛出异常,所有操作将回滚
  9. }
  10. }

四、高级特性应用

4.1 分页查询实现

集成分页插件(以PageHelper为例):

  1. 添加依赖:

    1. <dependency>
    2. <groupId>com.github.pagehelper</groupId>
    3. <artifactId>pagehelper-spring-boot-starter</artifactId>
    4. <version>1.4.7</version>
    5. </dependency>
  2. 使用示例:

    1. @GetMapping("/page")
    2. public PageInfo<User> getPage(
    3. @RequestParam(defaultValue = "1") int pageNum,
    4. @RequestParam(defaultValue = "10") int pageSize) {
    5. PageHelper.startPage(pageNum, pageSize);
    6. List<User> users = userMapper.selectAll();
    7. return new PageInfo<>(users);
    8. }

4.2 多数据源配置

对于需要连接多个数据库的场景:

  1. @Configuration
  2. public class DataSourceConfig {
  3. @Bean
  4. @ConfigurationProperties("spring.datasource.primary")
  5. public DataSource primaryDataSource() {
  6. return DataSourceBuilder.create().build();
  7. }
  8. @Bean
  9. @ConfigurationProperties("spring.datasource.secondary")
  10. public DataSource secondaryDataSource() {
  11. return DataSourceBuilder.create().build();
  12. }
  13. @Bean
  14. public SqlSessionFactory primarySqlSessionFactory(DataSource primaryDataSource) throws Exception {
  15. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
  16. bean.setDataSource(primaryDataSource);
  17. bean.setMapperLocations(new PathMatchingResourcePatternResolver()
  18. .getResources("classpath:mapper/primary/*.xml"));
  19. return bean.getObject();
  20. }
  21. }

五、调试与优化技巧

  1. SQL日志监控:在配置文件中开启SQL日志

    1. logging:
    2. level:
    3. com.example.mapper: debug
  2. 性能优化建议

    • 使用@CacheNamespace实现二级缓存
    • 对频繁查询的字段添加索引
    • 避免N+1查询问题,使用<association><collection>进行关联查询
  3. 常见问题排查

    • Invalid bound statement错误:检查Mapper接口与XML文件的namespace是否一致
    • Table doesn't exist错误:确认数据库表名与实体类注解配置

六、完整项目示例

GitHub示例仓库(中立化描述):某代码托管平台提供完整项目模板,包含以下特性:

  • 基于Spring Boot 3.2.0 + MyBatis 3.5.13
  • 集成Swagger API文档
  • 包含单元测试用例
  • 提供Docker部署脚本

通过本文的实践指导,开发者可以快速掌握Spring Boot与MyBatis的整合开发技巧,构建出高效稳定的数据库操作层。对于毕业设计项目,建议在此基础上扩展权限管理、日志记录等企业级功能模块。