SpringBoot整合MyBatis-Plus实战与优化指南

1. SpringBoot与MyBatis-Plus整合概述

在Java企业级开发中,数据持久层框架的选择直接影响开发效率和系统性能。MyBatis-Plus作为MyBatis的增强工具,在保留MyBatis所有特性的基础上,提供了更多便捷功能。与SpringBoot的整合能够极大简化传统SSM框架的配置复杂度,实现开箱即用的效果。

我经历过多个从零搭建的企业级项目,发现合理的依赖管理和配置可以避免后期80%的兼容性问题。特别是在SpringBoot 2.x/3.x版本交替的当下,很多团队都遇到过依赖冲突导致启动失败的状况。本文将基于最新稳定版本,详解如何正确整合这两个框架。

2. 环境准备与工程初始化

2.1 基础环境要求

  • JDK 1.8+(推荐JDK 17)
  • Maven 3.6+或Gradle 7.x
  • SpringBoot 2.7.x/3.0.x
  • MySQL 5.7+/H2(测试用)

注意:MyBatis-Plus 3.5.x开始支持SpringBoot 3.x,但需要对应使用mybatis-plus-spring-boot3-starter

2.2 创建SpringBoot项目

通过以下任一方式初始化项目:

  1. IDEA新建项目选择Spring Initializr
  2. 访问 start.spring.io 生成基础项目
  3. 命令行使用spring init

关键依赖选择:

  • Spring Web
  • Lombok(可选但推荐)
  • 对应数据库驱动(MySQL/H2)

3. 完整依赖配置方案

3.1 Maven依赖配置

根据SpringBoot版本选择对应starter:

<!-- SpringBoot 2.x 项目 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.17</version> </dependency> <!-- SpringBoot 3.x 项目 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-spring-boot3-starter</artifactId> <version>3.5.17</version> </dependency>

必须配套的依赖:

<!-- 数据库连接池(以HikariCP为例) --> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> </dependency> <!-- 数据库驱动(以MySQL为例) --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- Lombok(推荐) --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>

3.2 常见依赖冲突解决

  1. 与MyBatis原生包冲突

    • 移除mybatis-spring-boot-starter
    • 确保只保留MyBatis-Plus的starter
  2. 分页插件冲突

    <exclusions> <exclusion> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> </exclusion> </exclusions>
  3. Jackson版本问题

    <properties> <jackson.version>2.15.2</jackson.version> </properties>

4. 核心配置详解

4.1 基础YML配置

spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/mp_demo?useSSL=false&serverTimezone=Asia/Shanghai username: root password: 123456 hikari: maximum-pool-size: 20 minimum-idle: 5 mybatis-plus: configuration: map-underscore-to-camel-case: true # 自动驼峰转换 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # SQL日志 global-config: db-config: id-type: auto # 主键策略 logic-delete-field: deleted # 逻辑删除字段 logic-delete-value: 1 logic-not-delete-value: 0

4.2 Java配置类(可选)

@Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // 分页插件 interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 乐观锁插件 interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return interceptor; } @Bean public ISqlInjector sqlInjector() { return new DefaultSqlInjector(); } }

5. 编码实现与测试

5.1 实体类定义

@Data @TableName("sys_user") public class User { @TableId(type = IdType.AUTO) private Long id; private String username; @TableField("pwd") private String password; private Integer age; @TableLogic private Integer deleted; }

5.2 Mapper接口

public interface UserMapper extends BaseMapper<User> { // 自定义SQL示例 @Select("SELECT * FROM sys_user WHERE age > #{age}") List<User> selectByAge(@Param("age") Integer age); }

5.3 启动类配置

@SpringBootApplication @MapperScan("com.example.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

5.4 功能测试

@SpringBootTest class UserMapperTest { @Autowired private UserMapper userMapper; @Test void testCRUD() { // 插入 User user = new User(); user.setUsername("test"); user.setPassword("123"); userMapper.insert(user); // 查询 List<User> users = userMapper.selectList( new QueryWrapper<User>().gt("age", 18) ); // 更新 user.setAge(20); userMapper.updateById(user); // 删除 userMapper.deleteById(1L); } }

6. 高级配置与优化

6.1 多数据源配置

@Configuration @MapperScan(basePackages = "com.example.mapper.db1", sqlSessionTemplateRef = "db1SqlSessionTemplate") public class DataSource1Config { @Bean @ConfigurationProperties("spring.datasource.db1") public DataSource db1DataSource() { return DataSourceBuilder.create().build(); } @Bean public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception { MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean(); factory.setDataSource(dataSource); factory.setMapperLocations(new PathMatchingResourcePatternResolver() .getResources("classpath:mapper/db1/*.xml")); return factory.getObject(); } @Bean public SqlSessionTemplate db1SqlSessionTemplate( @Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } }

6.2 性能优化建议

  1. 批量操作

    userMapper.insertBatchSomeColumn(list);
  2. SQL打印优化

    mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl
  3. 二级缓存配置

    @CacheNamespace public interface UserMapper extends BaseMapper<User> {}

7. 常见问题排查

7.1 启动时报错解决方案

  1. Failed to configure a DataSource

    • 检查数据库连接配置
    • 确保驱动包存在
  2. No qualifying bean of type 'xxxMapper'

    • 确认@MapperScan路径正确
    • 检查Mapper接口是否继承BaseMapper
  3. SQL语法错误

    • 检查实体类@TableName注解
    • 验证字段映射关系

7.2 开发调试技巧

  1. SQL日志格式化

    logging: level: com.baomidou.mybatisplus: debug
  2. 自动生成代码: 使用MyBatis-Plus Generator快速生成Entity/Mapper/Service代码

  3. Wrapper使用技巧

    new QueryWrapper<User>() .select("id", "name") .like("name", "张") .between("age", 20, 30) .orderByDesc("create_time");

在实际项目开发中,我发现合理的分库分表策略配合MyBatis-Plus的动态表名插件,可以优雅地解决数据分片问题。另外,对于复杂查询场景,建议使用@Select注解编写原生SQL,既保持灵活性又避免XML配置的繁琐