MyBatis-Plus 与 Spring Boot 集成原理实战示例
作者:csdn_tom_168
下面是对 MyBatis-Plus 与 Spring Boot 集成原理的源码级深度分析,涵盖自动配置、核心组件、启动流程、关键类解析以及与原生 MyBatis 的差异。通过本篇分析,你将彻底理解 MyBatis-Plus 是如何在 Spring Boot 环境中实现“开箱即用”的。
🌟 一、MyBatis-Plus 简介
MyBatis-Plus(简称 MP) 是基于 MyBatis 的增强工具,完全兼容 MyBatis,提供了:
- 无需写 SQL 的 CRUD 操作(
IService/BaseMapper) - 自动分页插件
- 逻辑删除
- 自动填充字段(如
create_time) - 代码生成器
- 性能分析插件
它并不是替代 MyBatis,而是对 MyBatis 的“增强 + 自动化”。
🧩 二、集成方式(Spring Boot)
1. 引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>⚠️ 注意:使用 mybatis-plus-boot-starter 而非 mybatis-plus,它会自动引入 mybatis-spring 并触发自动配置。
🔧 三、核心机制:自动配置(Auto Configuration)
1. 自动配置入口
Spring Boot 启动时,会加载:
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
内容包含:
com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration
✅ 这是 MP 的自动配置类,由 Spring Boot 2.4+ 的新机制加载。
2.MybatisPlusAutoConfiguration核心功能
@Configuration
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties(MybatisPlusProperties.class)
@AutoConfigureAfter({DataSourceAutoConfiguration.class})
public class MybatisPlusAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
// 设置 MyBatis-Plus 全局配置、插件、扫描路径等
return factoryBean.getObject();
}
@Bean
@ConditionalOnMissingBean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
@Bean
@ConditionalOnProperty(prefix = "mybatis-plus", name = "mapper-locations")
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer configurer = new MapperScannerConfigurer();
configurer.setBasePackage(mybatisPlusProperties.getMapperLocations());
return configurer;
}
}📌 本质:在原生 MyBatis 集成 Spring 的基础上,做了增强和默认配置。
🏗️ 四、MyBatis-Plus 核心增强组件
1.MybatisSqlSessionFactoryBean—— 增强版工厂
继承自 SqlSessionFactoryBean,但做了以下增强:
| 功能 | 说明 |
|---|---|
| 自动注入全局配置 | 如 GlobalConfig(ID 生成策略、逻辑删除等) |
| 自动注册核心插件 | 如 PaginationInnerInterceptor(分页)、LogicDeleteInnerInterceptor(逻辑删除) |
支持 @DS 多数据源 | 集成 dynamic-datasource-spring-boot-starter |
// 自动添加分页插件
if (globalConfig.getDbConfig().isEnableSqlRunner()) {
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
}
2.BaseMapper<T>—— 通用 Mapper 接口
public interface BaseMapper<T> extends Mapper<T> {
int insert(T entity);
T selectById(Serializable id);
int updateById(T entity);
int deleteById(Serializable id);
// ... 更多方法
}
- 继承自 MyBatis 的
Mapper<T>,但提供了默认 SQL 实现(通过 MP 内部 SQL 构造器自动生成)。 - 无需 XML 或
@Select注解,即可使用 CRUD。
📌 原理:MP 在启动时,通过
MapperRegistry扫描所有继承BaseMapper的接口,并为其生成 SQL。
3.IService<T>与ServiceImpl<M,T>—— 服务层增强
public interface UserService extends IService<User> {}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {}ServiceImpl<M,T>内部持有baseMapper,调用BaseMapper方法。- 提供
saveBatch()、list()、page()等批量操作。
4.MybatisPlusInterceptor—— 核心插件链
MP 将多个功能封装为 Inner Interceptor,统一注册到 MybatisPlusInterceptor:
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
interceptor.addInnerInterceptor(new LogicDeleteInnerInterceptor());
interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor()); // 防止全表更新/删除
return interceptor;
}| 插件 | 作用 |
|---|---|
PaginationInnerInterceptor | 分页支持(替换 PageHelper) |
LogicDeleteInnerInterceptor | 逻辑删除(自动改写 SQL:WHERE deleted=0) |
BlockAttackInnerInterceptor | 阻止无 WHERE 条件的 UPDATE/DELETE |
TenantLineInnerInterceptor | 多租户支持 |
📌 所有插件基于 MyBatis 的
Executor拦截机制实现。
🚀 五、启动流程源码剖析
flowchart TD
A[Spring Boot 启动] --> B[加载 MybatisPlusAutoConfiguration]
B --> C[创建 SqlSessionFactory]
C --> D[MybatisSqlSessionFactoryBean.build()]
D --> E[解析 Mapper 接口]
E --> F[MP 扫描 BaseMapper 子接口]
F --> G[生成默认 SQL(通过 SqlMethod 枚举)]
G --> H[注册 MappedStatement]
H --> I[注入 MybatisPlusInterceptor]
I --> J[Mapper 代理对象创建]
J --> K[Service 层注入 Mapper]
K --> L[应用就绪]
关键源码入口:
| 类 | 作用 |
|---|---|
MybatisPlusAutoConfiguration | 自动配置主类 |
MybatisSqlSessionFactoryBean | 构建 SqlSessionFactory,注入 MP 特性 |
DefaultSqlSession | 执行 SQL,MP 的 SQL 已注册为 MappedStatement |
MapperRegistry | 扫描 Mapper 接口 |
SqlMethod 枚举 | 定义所有默认 SQL 模板(如 INSERT, SELECT_BY_ID) |
🧠 六、MP 如何生成默认 SQL?
MP 在启动时,为每个 BaseMapper 方法预定义了 SQL 模板:
public enum SqlMethod {
INSERT("insert", "插入一条数据", "<script>INSERT INTO %s %s VALUES %s</script>");
// 更多...
}
通过 AbstractMethod 实现类(如 Insert)生成 MappedStatement:
// org.apache.ibatis.session.Configuration mappedStatements.put(ms.getId(), ms); // 注册到 MyBatis 全局配置
调用 userMapper.insert(user) 时,实际执行的是这个预生成的 SQL。
🧩 七、与原生 MyBatis 集成对比
| 功能 | 原生 MyBatis | MyBatis-Plus |
|---|---|---|
| CRUD SQL | 手写(XML 或注解) | 自动生成 |
| 分页 | 手写或 PageHelper 插件 | 内置 Page<T> + PaginationInnerInterceptor |
| 逻辑删除 | 手动写 WHERE deleted=0 | 配置 mybatis-plus.global-config.db-config.logic-delete-value |
| 字段自动填充 | 自定义 MetaObjectHandler | 支持 @TableField(fill = FieldFill.INSERT) |
| 代码生成 | 手动或第三方工具 | 内置 AutoGenerator |
| 配置方式 | 手动配置 SqlSessionFactoryBean | 自动配置,零配置启动 |
✅ 八、常见配置(application.yml)
mybatis-plus:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.entity
configuration:
map-underscore-to-camel-case: true
global-config:
db-config:
id-type: auto
logic-delete-value: 1
logic-not-delete-value: 0
configuration:
auto-mapping-behavior: full🛑 九、注意事项与坑点
| 问题 | 解决方案 |
|---|---|
Mapped Statements collection does not contain... | 检查 @MapperScan 是否扫描到 Mapper 接口 |
| 分页无效 | 确保 MybatisPlusInterceptor 中注册了 PaginationInnerInterceptor |
| 逻辑删除不生效 | 检查实体类字段是否有 @TableLogic 注解 |
| 多数据源冲突 | 使用 dynamic-datasource-spring-boot-starter + @DS |
| 自定义 SQL 与 MP 冲突 | 使用 @Options(useCache = false, flushCache = FlushCachePolicy.TRUE) |
✅ 总结:MyBatis-Plus 与 Spring Boot 集成的本质
MyBatis-Plus = MyBatis + Auto Configuration + Default SQL + Core Plugins
| 核心思想 | 说明 |
|---|---|
| 零配置启动 | 通过 mybatis-plus-boot-starter 自动装配 |
| 无侵入增强 | 不改变 MyBatis 核心,只做扩展 |
| 约定优于配置 | 提供合理的默认值(如分页、ID 生成) |
| 插件化设计 | 所有功能通过 InnerInterceptor 实现 |
如果你需要:
- MyBatis-Plus 分页执行流程图(Mermaid)
- 自动填充源码分析
- 代码生成器(Code Generator)原理
欢迎继续提问,我可以为你生成对应的源码图解与实战示例!
到此这篇关于MyBatis-Plus 与 Spring Boot 集成原理实战示例的文章就介绍到这了,更多相关MyBatis-Plus 与 Spring Boot 集成内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
