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

发布时间:2026/7/21 20:35:41
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 17Maven 3.6或Gradle 7.xSpringBoot 2.7.x/3.0.xMySQL 5.7/H2测试用注意MyBatis-Plus 3.5.x开始支持SpringBoot 3.x但需要对应使用mybatis-plus-spring-boot3-starter2.2 创建SpringBoot项目通过以下任一方式初始化项目IDEA新建项目选择Spring Initializr访问 start.spring.io 生成基础项目命令行使用spring init关键依赖选择Spring WebLombok可选但推荐对应数据库驱动MySQL/H23. 完整依赖配置方案3.1 Maven依赖配置根据SpringBoot版本选择对应starter!-- SpringBoot 2.x 项目 -- dependency groupIdcom.baomidou/groupId artifactIdmybatis-plus-boot-starter/artifactId version3.5.17/version /dependency !-- SpringBoot 3.x 项目 -- dependency groupIdcom.baomidou/groupId artifactIdmybatis-plus-spring-boot3-starter/artifactId version3.5.17/version /dependency必须配套的依赖!-- 数据库连接池以HikariCP为例 -- dependency groupIdcom.zaxxer/groupId artifactIdHikariCP/artifactId /dependency !-- 数据库驱动以MySQL为例 -- dependency groupIdmysql/groupId artifactIdmysql-connector-java/artifactId scoperuntime/scope /dependency !-- Lombok推荐 -- dependency groupIdorg.projectlombok/groupId artifactIdlombok/artifactId optionaltrue/optional /dependency3.2 常见依赖冲突解决与MyBatis原生包冲突移除mybatis-spring-boot-starter确保只保留MyBatis-Plus的starter分页插件冲突exclusions exclusion groupIdcom.github.pagehelper/groupId artifactIdpagehelper-spring-boot-starter/artifactId /exclusion /exclusionsJackson版本问题properties jackson.version2.15.2/jackson.version /properties4. 核心配置详解4.1 基础YML配置spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/mp_demo?useSSLfalseserverTimezoneAsia/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: 04.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 BaseMapperUser { // 自定义SQL示例 Select(SELECT * FROM sys_user WHERE age #{age}) ListUser 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); // 查询 ListUser users userMapper.selectList( new QueryWrapperUser().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 性能优化建议批量操作userMapper.insertBatchSomeColumn(list);SQL打印优化mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl二级缓存配置CacheNamespace public interface UserMapper extends BaseMapperUser {}7. 常见问题排查7.1 启动时报错解决方案Failed to configure a DataSource检查数据库连接配置确保驱动包存在No qualifying bean of type xxxMapper确认MapperScan路径正确检查Mapper接口是否继承BaseMapperSQL语法错误检查实体类TableName注解验证字段映射关系7.2 开发调试技巧SQL日志格式化logging: level: com.baomidou.mybatisplus: debug自动生成代码 使用MyBatis-Plus Generator快速生成Entity/Mapper/Service代码Wrapper使用技巧new QueryWrapperUser() .select(id, name) .like(name, 张) .between(age, 20, 30) .orderByDesc(create_time);在实际项目开发中我发现合理的分库分表策略配合MyBatis-Plus的动态表名插件可以优雅地解决数据分片问题。另外对于复杂查询场景建议使用Select注解编写原生SQL既保持灵活性又避免XML配置的繁琐