当前位置: 首页 > news >正文

Mybatis-Plus源代码走读后记

文章目录

  • 前言
  • 框架结构
  • 一、启动时操作:数据库配置,Mapper扫描等
    • 1.1 自动装配
    • 1.2 Sql会话工厂:MybatisSqlSessionFactoryBean
    • 1.3 抽象Sql注入类:AbstractSqlInjector.class
    • 1.4 主流程线:循环遍历集合AbstractMethod,注入自定义方法
    • 1.5 MappedStatement对象
  • 二、CRUD交互
    • 1.启动时扫描mapper接口类的bean定义
    • 2.MybatisMapperProxy代理类
    • 3.SqlSession操作数据表CURD
  • 三、附录


前言

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
Mybatis-Plus核心特性:

  1. 代码生成器(Generator)
  2. 启动时操作:数据库配置,Mapper扫描等
  3. 实体资源的CRUD操作、交互

框架结构

pic


一、启动时操作:数据库配置,Mapper扫描等

完成CRUD sql对象MappedStatement注入到Configuration配置中,即实现sql自动注入。

1.1 自动装配

mybatis-plus-spring-boot-autoconfigure module模块:
spring.factories 项目启动进行自动配置,自动启动类

**MybatisPlusAutoConfiguration**
......

MybatisPlusAutoConfiguration实现InitializingBean接口,主要:
1-获取afterPropertiesSet()方法,在Bean初始化后会自动调用
2-在未配置SqlSessionFactory、SqlSessionTemplate、MapperFactory-Bean时会由SpringBoot创建Bean,并且保存到容器中。

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({SqlSessionFactory.class, 
SqlSessionFactoryBean.class})
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties(MybatisPlusProperties.class)
@AutoConfigureAfter({DataSourceAutoConfiguration.class, 
MybatisPlusLanguageDriverAutoConfiguration.class})
public class MybatisPlusAutoConfiguration implements 
InitializingBean {private final MybatisPlusProperties properties;....../**afterPropertiesSet 方法用于在 Bean 初始化时,遍历并执行所有 MybatisPlusPropertiesCustomizer 实现类的 customize 方法,对 MyBatis Plus 的配置属性进行自定义修改,然后调用checkConfigFileExists() 检查配置文件是否存在*/@Overridepublic void afterPropertiesSet() {if (!CollectionUtils.isEmpty(mybatisPlusPropertiesCustomizers)) {mybatisPlusPropertiesCustomizers.forEach(i -> i.customize(properties));}checkConfigFileExists();}private void checkConfigFileExists() {if (this.properties.isCheckConfigLocation()&&StringUtils.hasText(this.properties.getConfigLocation())) {Resource resource = this.resourceLoader.getResource(this.properties.getConfigLocation());Assert.state(resource.exists(),"Cannot find config location: " + resource + " + " (please add config file or check your "+ "Mybatis configuration)");}}......//1:实例化SqlSessionFactory,创建MybatisSqlSessionFactoryBean@Bean@ConditionalOnMissingBeanpublic SqlSessionFactory sqlSessionFactory(DataSourcedataSource) throws Exception {***MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();***factory.setDataSource(dataSource);factory.setVfs(SpringBootVFS.class);factory.setApplicationContext(this.applicationContext);......applyConfiguration(factory);......applySqlSessionFactoryBeanCustomizers(factory);GlobalConfig globalConfig = this.properties.getGlobalConfig();this.getBeanThen(MetaObjectHandler.class, globalConfig::setMetaObjectHandler);......factory.setGlobalConfig(globalConfig);***return factory.getObject();***}......//2:实例化SqlSessionTemplate @Bean@ConditionalOnMissingBeanpublic SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {ExecutorType executorType = this.properties.getExecutorType();if (executorType != null) {return new SqlSessionTemplate(sqlSessionFactory, executorType);} else {return new SqlSessionTemplate(sqlSessionFactory);}}...... //3:引入AutoConfiguredMapperScannerRegistrar、MapperFactoryBean@Import(AutoConfiguredMapperScannerRegistrar.class)@ConditionalOnMissingBean({MapperFactoryBean.class, MapperScannerConfigurer.class})public static class MapperScannerRegistrarNotFoundConfiguration implements InitializingBean {@Overridepublic void afterPropertiesSet() {logger.debug("Not found configuration for registering mapper"+"bean using @MapperScan, MapperFactoryBean and "+"MapperScannerConfigurer.");}}......
}

1.2 Sql会话工厂:MybatisSqlSessionFactoryBean

1.实现三个接口FactoryBean, InitializingBean, ApplicationListener。其中:ApplicationListener监听器,监听ApplicationContext初始化或者刷新事件,用来刷新MappedStatement。

2.MybatisSqlSessionFactoryBean getObject()方法被MybatisPlusAutoConfiguration类factory.getObject()调用。

public class MybatisSqlSessionFactoryBean implements 
FactoryBean<SqlSessionFactory>, 
InitializingBean, 
ApplicationListener<ContextRefreshedEvent> {......//1.监听SqlSessionFactory中的所有已注册的SQL映射语句名称,//用于提前发现配置错误public void onApplicationEvent(ContextRefreshedEvent event) {if (this.failFast) {this.sqlSessionFactory.getConfiguration().getMappedStatementNames();}}....../*MybatisPlusAutoConfiguration类factory.getObject()调用class SqlSessionFactory sqlSessionFactory(){MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();......return factory.getObject();*///当sqlSessionFactory为空,调用afterPropertiesSet()public SqlSessionFactory getObject() throws Exception {if (this.sqlSessionFactory == null) {this.afterPropertiesSet();}return this.sqlSessionFactory;}......public void afterPropertiesSet() throws Exception {this.sqlSessionFactory = this.buildSqlSessionFactory();}......//创建SqlSessionFactory 核心代码片断protected SqlSessionFactory buildSqlSessionFactory() throws Exception {MybatisXMLConfigBuilder xmlConfigBuilder = null;Object targetConfiguration;Optional var10000;if (this.configuration != null) {targetConfiguration = this.configuration;//根据 configLocation 加载配置文件this.globalConfig.setDbConfig((GlobalConfig.DbConfig)     Optional.ofNullable(this.globalConfig.getDbConfig()).orElseGet(GlobalConfig.DbConfig::new));//扫描别名包、添加拦截器插件targetConfiguration.getTypeAliasRegistry().registerAlias(typeAlias);targetConfiguration.addInterceptor(plugin);targetConfiguration.getTypeHandlerRegistry().register(typeHandler);//根据mapperLocations解析Mapper文件MybatisXMLMapperBuilder xmlMapperBuilder = new MybatisXMLMapperBuilder(mapperLocation.getInputStream(), (Configuration)targetConfiguration, mapperLocation.toString(),((Configuration)targetConfiguration).getSqlFragments());***xmlMapperBuilder.parse();***//构建 SqlSessionFactorySqlSessionFactory sqlSessionFactory =  this.sqlSessionFactoryBuilder.build((Configuration)targetConfiguration);}return sqlSessionFactory;}......
}

深入xmlMapperBuilder.parse()跟踪,MybatisMapperAnnotationBuilder.class

public class MybatisMapperAnnotationBuilder extends MapperAnnotationBuilder {public void parse() {String resource = this.type.toString();if (!this.configuration.isResourceLoaded(resource)) {this.loadXmlResource();this.configuration.addLoadedResource(resource);this.parseResultMap(method);this.parseStatement(method);try {if (GlobalConfigUtils.isSupperMapperChildren(this.configuration, this.type)) {this.parserInjector();}}}this.configuration.parsePendingMethods(false);}void parserInjector() {     GlobalConfigUtils.getSqlInjector(this.configuration)***.inspectInject(this.assistant, this.type);***}  
}

1.3 抽象Sql注入类:AbstractSqlInjector.class

抽象类 AbstractSqlInjector,用于在 MyBatis Plus 中动态注入 SQL 方法。其主要功能如下:

  • 获取实体类类型:通过反射获取当前 Mapper 对应的实体类(modelClass)。
  • 避免重复注入:使用全局缓存mapperRegistryCache 防止对同一个 Mapper 类重复注入。
  • 初始化表信息:调用TableInfoHelper.initTableInfo 初始化数据库表与实体类的映射信息。
  • 获取并执行注入方法:通过getMethodList 获取需注入的方法列表,并逐个调用其 inject 方法进行 SQL 注入。
public void inspectInject(MapperBuilderAssistant builderAssistant, 
Class<?> mapperClass) {Class<?> modelClass = ReflectionKit.getSuperClassGeneric-Type(mapperClass, Mapper.class, 0);if (modelClass != null) {String className = mapperClass.toString();Set<String> mapperRegistryCache = GlobalConfigUtils.getMapperRegistryCache(builderAssistant.getConfiguration());if (!mapperRegistryCache.contains(className)) {TableInfo tableInfo =TableInfoHelper.initTableInfo(builderAssistant, modelClass);//1.获取通用的自定义方法List<AbstractMethod> methodList = this.getMethodList(mapperClass, tableInfo);if (CollectionUtils.isEmpty(methodList)) {methodList = this.getMethodList(builderAssistant.getConfiguration(), mapperClass, tableInfo);}if (CollectionUtils.isNotEmpty(methodList)) {//2.循环遍历集合AbstractMethod,注入自定义方法***methodList.forEach((m) -> {m.inject(builderAssistant, mapperClass, modelClass, tableInfo);});***}mapperRegistryCache.add(className);}}}

子流程线:1.获取通用的自定义方法
DefaultSqlInjector 类实现 AbstractSqlInjector 类getMethodList(mapperClass, tableInfo)。
getMethodList 获取需注入的方法列表。

public class DefaultSqlInjector extends AbstractSqlInjector {public List<AbstractMethod> getMethodList(Configuration configuration, Class<?> mapperClass, TableInfo tableInfo) {GlobalConfig.DbConfig dbConfig = GlobalConfigUtils.getDbConfig(configuration);Stream.Builder<AbstractMethod> builder = Stream.builder().add(new Insert(dbConfig.isInsertIgnoreAutoIncrementColumn())).add(new Delete()).add(new Update()).add(new SelectCount()).add(new SelectMaps()).add(new SelectObjs()).add(new SelectList());if (tableInfo.havePK()) {builder.add(new DeleteById()).add(new DeleteByIds()).add(new UpdateById()).add(new SelectById()).add(new SelectByIds());} return (List)builder.build().collect(Collectors.toList());}
}

Insert :方法insert插入类

package com.baomidou.mybatisplus.core.injector.methods;
public class Insert extends AbstractMethod {private boolean ignoreAutoIncrementColumn;public Insert() {//见 enum SqlMethod 类定义方法(insert)模板this(SqlMethod.INSERT_ONE.getMethod());}public Insert(boolean ignoreAutoIncrementColumn) {this(SqlMethod.INSERT_ONE.getMethod());this.ignoreAutoIncrementColumn = ignoreAutoIncrementColumn;} ......
}

enum SqlMethod 类:定义各方法(insert/update 等)字符模板

public enum SqlMethod {INSERT_ONE("insert", "插入一条数据(选择字段插入)", "<script>\nINSERT INTO %s %s VALUES %s\n</script>"),UPSERT_ONE("upsert", "Phoenix插入一条数据(选择字段插入)", "<script>\nUPSERT INTO %s %s VALUES %s\n</script>"),DELETE_BY_ID("deleteById", "根据ID 删除一条数据", "DELETE FROM %s WHERE %s=#{%s}"),.......
}

1.4 主流程线:循环遍历集合AbstractMethod,注入自定义方法

入口代码:

public abstract class AbstractSqlInjector implements ISqlInjector {public void inspectInject(MapperBuilderAssistant builderAssistant,Class<?> mapperClass) {(AbstractMethod)methodList.forEach((m) -> {m.inject(builderAssistant, mapperClass, modelClass, tableInfo);});}
}

AbstractMethod 定义 inject方法:

public abstract class AbstractMethod implements Constants {public void inject( MapperBuilderAssistant builderAssistant,Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo)  {......this.injectMappedStatement(mapperClass, modelClass, tableInfo);}....../*抽象方法injectMappedStatement由各继承子类(如Insert.classs/Update.class....../DeleteById)等重写、实现*/public abstract MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo);
}

AbstractMethod抽象类被各继承子类各继承子类继承,如下uml继承图:
在这里插入图片描述
AbstractMethod类injectMappedStatement(…)方法被各继承子类(如Insert.classs)重写、实现

package com.baomidou.mybatisplus.core.injector.methods;
public class Insert extends AbstractMethod {.....public MappedStatement injectMappedStatement(Class<?> mapper-Class,Class<?> modelClass, TableInfo tableInfo) {KeyGenerator keyGenerator = NoKeyGenerator.INSTANCE;SqlMethod sqlMethod = SqlMethod.INSERT_ONE;.....//构建Insert SQLString sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), columnScript, valuesScript);SqlSource sqlSource = super.createSqlSource(this.configuration, sql, modelClass);return this.***addInsertMappedStatement***(mapperClass, modelClass, this.methodName, sqlSource, (KeyGenerator)keyGenerator, keyProperty, keyColumn);}
}
备注:其它继承子类Update.class......DeleteById等同理都重写父类AbstractMethod-injectMappedStatement方法。

跟踪this.addInsertMappedStatement( …),最终进入MapperBuilderAssistant类

package org.apache.ibatis.builder;
public class MapperBuilderAssistant extends BaseBuilder {......public MappedStatement addMappedStatement(String id, SqlSource sqlSource, StatementType statementType, Integer timeout, String parameterMap, Class<?> parameterType, String resultMap,Class<?> resultType, ResultSetType resultSetType......) {if (this.unresolvedCacheRef) {throw new IncompleteElementException("Cache-ref not yet resolved");} else {id = this.applyCurrentNamespace(id, false);......//构建MappedStatement对象,设置各类属性如SQL来源、执行类型、结果映射等MappedStatement.Builder statementBuilder = (new MappedStatement.Builder(this.configuration, id, sqlSource, sqlCommandType)).....);......MappedStatement statement = statementBuilder.build();//构建好的MappedStatement注册到配置***this.configuration.addMappedStatement(statement);***return statement;}}
}

1.5 MappedStatement对象

将CRUD相关的sql对象MappedStatement注入到配置中,即实现sql自动注入,将预先定义好的sql和预先定义好的Mapper注册到MappedState-ment中。

class MybatisConfiguration extends Configuration {protected final Map<String, MappedStatement> mappedStatements;public void addMappedStatement(MappedStatement ms) {//判断MappedStatement是否存在,防止重复注入if (this.mappedStatements.containsKey(ms.getId())) {logger.error("mapper[" + ms.getId() + "] is ignored..");} else {//预先定义好的sql和预先定义好的Mapper注册到MappedStatement***this.mappedStatements.put(ms.getId(), ms);***}}
}

总结:
Mybatis-Plus SQL注入器机制‌:BaseMapper的insert方法实际由InsertMethod类(继承AbstractMethod)实现,通过SQL注入器动态注册到MyBatis容器中。关键步骤包括:
DefaultSqlInjector将InsertMethod注入到MappedStatement。


二、CRUD交互

资源实体Mapper接口(如角色表BaseRoleMapper) 继承BaseMapper,可继承源接口[增删改查]等方法。那么BaseMapper底层[增删改查]等操作同数据库表如何交互?

1.启动时扫描mapper接口类的bean定义

容器启动,扫描bean定义,加载 mapper接口类注册系列bean以及执行MybatisConfiguration getMapper()。

  • @MapperScan,通过@Import({MapperScannerRegistrar.class}) 引入MapperScannerRegistrar
  • MapperScannerRegistrar类: registerBeanDefinitions(…)方法:
    1).创建MapperScannerConfigurer的Bean定义构建器;
    2).设置各种属性值,如注解类型annotationClass、扫描路径basePackageClasses、过滤器Filters、作用域defaultScope、工厂Beans(mapperFactoryBean/sqlSessionTemplateBean
    /sqlSessionFactoryBeanName)等;
    3).将配置属性设置到Bean定义中;
    4).构建Bean定义注册到Spring容器中;
  • MapperScannerConfigurer引入ClassPathMapperScanner,进行basePackage扫描,流程:ClassPathMapperScanner#doScan(String… basePackages)
    -> processBeanDefinitions(Set beanDefinitions):
    1).设置 Mapper 接口信息:记录 Mapper 接口类名,并通过构造参数和属性注入到 MapperFactoryBean 中。
    2).设置工厂属性:根据配置注入 sqlSessionFactory、sqlSessionTemplate
  • Spring容器初始化已依赖注入Mapper接口的Bean,调用FactoryBean#getObject() 创建Mapper Bean 实例对象。
public class MapperFactoryBean<T> extends SqlSessionDaoSupportimplements FactoryBean<T>{......public T getObject() throws Exception {return this.getSqlSession().getMapper(this.mapperInterface);}......
}

getMapper()最终调用MybatisConfiguration.getMapper()

//MybatisConfiguration类
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {return this.mybatisMapperRegistry.getMapper(type, sqlSession);
}

MybatisMapperRegistry 类:

  • MybatisMapperRegistry 是对 MyBatis 框架中 MapperRegistry 的扩展或自定义实现。
  • 通过继承 MapperRegistry,可以重写或增强MyBatis 映射器接口的注册与管理逻辑。

MybatisConfiguration addMapper/getMapper执行过程图
在这里插入图片描述

2.MybatisMapperProxy代理类

目的: 对所有继承@Mapper接口的自定义类(如UserMapper用户类Mapper、RoleMapper角色类
Mapper)方法调用时进行拦截。

MybatisMapperRegistry#getMapper(Class type, SqlSession sqlSession)
在这里插入图片描述
代理工厂MybatisMapperProxyFactory创建代理类MybatisMapperProxy:

public class MybatisMapperProxyFactory<T> {protected T newInstance(MybatisMapperProxy<T> mapperProxy) {return Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);}
}

newProxyInstance()三个参数:

  • mapperInsterface.getClassLoader() :被代理接口的类加载器,即泛型T的类加载器。
  • new Class[]{mapperInterface} : 被代理接口。
  • mapperProxy :InvocationHandler的实现类MybatisMapperProxy(代理核心类),重写Object invoke(Object proxy, Method method, Object[] args)方法。
    在这里插入图片描述
    代理类MybatisMapperProxy:
    1)#invoke(Object proxy, Method method, Object[] args)方法:
    用于拦截接口方法调用。功能如下:如果调用的是 Object 类的方法(如 toString),则直接通过当前对象执行;否则,通过缓存的调用器执行方法-this.cachedInvoker(method).invoke(proxy, method, args, this.sqlSession);
    2)this.cachedInvoker(method):实例化MybatisMapperMethod类,并将MybatisMapperMethod类构建到创建PlainMethodInvoker对象内。
	new PlainMethodInvoker(new MybatisMapperMethod(this.mapperInterface, method, this.sqlSession.getConfiguration()));

3)调用PlainMethodInvoker.invoke(proxy, method, args, this.sqlSession)递归调用mapperMethod.execute(sqlSession, args);

private static class PlainMethodInvoker implements
MapperMethodInvoker {private final MybatisMapperMethod mapperMethod;.......public Object invoke(Object proxy, Method method, Object[] args, SqlSession sqlSession) throws Throwable {return **this.mapperMethod.execute(sqlSession, args)**;}}

4)MybatisMapperMethod 类
负责解析并执行 MyBatis 的 Mapper 接口方法,其核心功能如下:

  • 构造函数:初始化 SQL 命令信息和方法签名信息(如返回类型、参数处理)。
  • execute 方法:根据 SQL 类型(INSERT/UPDATE/DELETE/SELECT/FLUSH)调用相应的 SqlSession类对应方法执行数据库操作,并处理参数转换与结果封装。
  • 参数处理:通过convertArgsToSqlCommandParam将方法参数转换为 SQL 执行的参数格式。
  • 结果处理:对 SELECT 查询根据不同返回类型分别处理(单条、多条、Map、Cursor、IPage、Optional 等)。对增删改操作通过rowCountResult 处理影响行数的返回值。
public class MybatisMapperMethod {
.......public Object execute(SqlSession sqlSession, Object[] args){Object result;Object param;switch (this.command.getType()) {case INSERT:param = this.method.convertArgsToSqlCommandParam(args);result = this.rowCountResult(sqlSession.insert(this.command.getName(), param));break;case UPDATE:param = this.method.convertArgsToSqlCommandParam(args);result = this.rowCountResult(sqlSession.update(this.command.getName(), param));break;case DELETE:param = this.method.convertArgsToSqlCommandParam(args);result = this.rowCountResult(sqlSession.delete(this.command.getName(), param));break;case SELECT:if (this.method.returnsVoid() && this.method.hasResultHandler()) {this.executeWithResultHandler(sqlSession, args);result = null;} else if (this.method.returnsMany()) {result = this.executeForMany(sqlSession, args);} else if (this.method.returnsMap()) {result = this.executeForMap(sqlSession, args);} else if (this.method.returnsCursor()) {result = this.executeForCursor(sqlSession, args);} else if (IPage.class.isAssignableFrom(this.method.getReturnType())) {result = this.executeForIPage(sqlSession, args);} else {param = this.method.convertArgsToSqlCommandParam(args);result = sqlSession.selectOne(this.command.getName(), param);}break;case FLUSH:result = sqlSession.flushStatements();break;default:throw new BindingException("Unknown execution"+ "method for: " + this.command.getName());}.......return result;}.......
}

最终进入SqlSession#insert或#UPDATE等方法。

3.SqlSession操作数据表CURD

MyBatis-Plus的BaseMapper接口或自定义类(如UserMapper用户类Mapper、RoleMapper角色类Mapper)方法通过MybatisMapperProxy代理类操作后最终调用 SqlSession的update方法。
方法调用链‌(以update方法为样例):

	BaseMapper.update()MybatisMapperProxy.invoke()SqlSession.update()

DefaultSqlSession类继承接父类SqlSession,实现方法如下:
在这里插入图片描述
#getMappedStatement:获取SQL注入器事先注入至configuration内的mappedStatement
#this.executor.update :最终进入SimpleExecutor#doUpdate

public class DefaultSqlSession implements SqlSession {......public int update(String statement, Object parameter) {......MappedStatement ms = this.configuration.getMappedStatement(statement);this.executor.update(ms, this.wrapCollection(parameter));......}
}

SimpleExecutor#doUpdate
该处使用的url网络请求的数据。
PreparedStatementHandler#update
在这里插入图片描述
DruidPooledPreparedStatement#execute
调用 druid框架(com.alibaba.druid) jdbc驱动操作数据表

public boolean execute() throws SQLException {this.checkOpen();this.incrementExecuteCount();this.transactionRecord(this.sql);this.oracleSetRowPrefetch();this.conn.beforeExecute();......var1 = this.stmt.execute();......return var1;}

或 PreparedStatementWrapper#execute
调用 mysql jdbc(mysql-connector-j) 驱动操作数据表

package com.mysql.cj.jdbc;public class PreparedStatementWrapper extends StatementWrapper implements PreparedStatement {......public boolean execute() throws SQLException {return ((PreparedStatement)this.wrappedStmt).execute();}......
}

最终完成与对应数据源的数据库CURD交互。


三、附录

官网
简介
指南
Spring Mybatis-Plus yml文件自动配置属性结构:

{"groups": [{"sourceType": "com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties","name": "mybatis-plus","type": "com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties"},{"sourceType": "com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties","name": "mybatis-plus.configuration","sourceMethod": "getConfiguration()","type": "com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties$CoreConfiguration"},{"sourceType": "com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties","name": "mybatis-plus.global-config","sourceMethod": "getGlobalConfig()","type": "com.baomidou.mybatisplus.core.config.GlobalConfig"},{"sourceType": "com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig","name": "mybatis-plus.global-config.db-config","sourceMethod": "getDbConfig()","type": "com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig"}],"properties": [{"defaultValue": false,"name": "mybatis-plus.lazy-initialization","description": "Set whether enable lazy initialization for mapper bean.","type": "java.lang.Boolean"},{"defaultValue": "","name": "mybatis-plus.mapper-default-scope","description": "A default scope for mapper bean that scanned by auto-configure.","type": "java.lang.String"},{"defaultValue": true,"name": "mybatis-plus.inject-sql-session-on-mapper-scan","description": "Set whether inject a SqlSessionTemplate or SqlSessionFactory bean (If you want to back to the behavior of 2.2.1 or before, specify false). If you use together with spring-native, should be set true.","type": "java.lang.Boolean"},{"sourceType": "com.baomidou.mybatisplus.core.config.GlobalConfig","name": "mybatis-plus.global-config.identifier-generator","deprecation": {"level": "error","reason": "请使用@Bean的方式注入至Spring容器."}},{"sourceType": "com.baomidou.mybatisplus.core.config.GlobalConfig","name": "mybatis-plus.global-config.meta-object-handler","deprecation": {"level": "error","reason": "3.0开始废除此属性,请使用@Bean的方式注入至Spring容器."}},{"sourceType": "com.baomidou.mybatisplus.core.config.GlobalConfig","name": "mybatis-plus.global-config.sql-injector","deprecation": {"level": "error","reason": "3.0开始废除此属性,请使用@Bean的方式注入至Spring容器."}},{"sourceType": "com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig","name": "mybatis-plus.global-config.db-config.key-generator","deprecation": {"level": "error","reason": "3.0开始废除此属性,请使用@Bean的方式注入至Spring容器."}},{"sourceType": "com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties","name": "mybatis-plus.default-scripting-language-driver","defaultValue": "com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver","type": "java.lang.Class<? extends org.apache.ibatis.scripting.LanguageDriver>"},{"sourceType": "com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties$CoreConfiguration","name": "mybatis-plus.configuration.default-scripting-language","defaultValue": "com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver","type": "java.lang.Class<? extends org.apache.ibatis.scripting.LanguageDriver>","deprecation": {"level": "error","reason": "设置无效.","replacement": "mybatis-plus.configuration.default-scripting-language-driver"}},{"sourceType": "com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties$CoreConfiguration","name": "mybatis-plus.configuration.default-enum-type-handler","defaultValue": "org.apache.ibatis.type.EnumTypeHandler","description": "A default TypeHandler class for Enum.","type": "java.lang.Class<? extends org.apache.ibatis.type.TypeHandler>"}]
}

说明:

  • groups:定义了MyBatis-Plus配置的层级结构和对应的Java类.
  • properties:列出可配置的参数及其默认值、类型、描述和弃用信息.
    例如:
mybatis-plus:mapper-locations:- classpath*:mapper_**/**/*Mapper.xml#实体扫描,多个package用逗号或者分号分隔typeAliasesPackage: top.tangyh.lamp.*.entity;top.tangyh.basic.database.mybatis.typehandlertypeEnumsPackage: top.tangyh.lamp.*.enumerationglobal-config:db-config:id-type: INPUTinsert-strategy: NOT_NULLupdate-strategy: NOT_NULLselect-strategy: NOT_EMPTYconfiguration:#配置返回数据库(column下划线命名&&返回java实体是驼峰命名),#自动匹配无需as(没开启这个,SQL需要写as:#select user_id as userId)map-underscore-to-camel-case: truecache-enabled: false#配置JdbcTypeForNull, oracle数据库必须配置jdbc-type-for-null: 'null'

配置类:
mybatis-plus-spring-boot-autoconfigure module:

package com.baomidou.mybatisplus.autoconfigure;
@Data
@Accessors(chain = true)
@ConfigurationProperties(prefix = Constants.MYBATIS_PLUS)
public class MybatisPlusProperties {...........private CoreConfiguration configuration;@NestedConfigurationPropertyprivate GlobalConfig globalConfig = GlobalConfigUtils.defaults();}

mybatis-plus-core module:

package com.baomidou.mybatisplus.core.config;
/*** Mybatis 全局缓存** @author Caratacus* @since 2016-12-06*/
@Data
@Accessors(chain = true)
public class GlobalConfig implements Serializable {.........../*** 数据库相关配置*/private DbConfig dbConfig;...........@Datapublic static class DbConfig {/*** 主键类型*/private IdType idType = IdType.ASSIGN_ID;/*** 表名是否使用驼峰转下划线命名,只对表名生效*/private boolean tableUnderline = true;/*** 大写命名,对表名和字段名均生效*/private boolean capitalMode = false;/*** 表主键生成器*/private List<IKeyGenerator> keyGenerators;.........../*** 字段验证策略之 insert** @since 3.1.2*/private FieldStrategy insertStrategy = FieldStrategy.NOT_NULL;/*** 字段验证策略之 update** @since 3.1.2*/private FieldStrategy updateStrategy = FieldStrategy.NOT_NULL;/*** 字段验证策略之 where** @since 3.4.4*/private FieldStrategy whereStrategy = FieldStrategy.NOT_NULL;/*** 生成INSERT语句时忽略自增主键字段(默认不忽略,* 主键有值时写入主键值,无值自增).* <p>当设置为true时,执行生成SQL语句无论ID是否有值都会忽视*  (此为3.4.3.1版本下策略,如果升级遇到问题可以考虑开启* 此配置来兼容升级)</p>** @since 3.5.6*/private boolean insertIgnoreAutoIncrementColumn = false;}
}
http://www.lryc.cn/news/575838.html

相关文章:

  • 青少年编程与数学 01-012 通用应用软件简介 15 人工智能助手
  • Rust交互式编程环境Jupyter Lab搭建
  • YOLOv8快速入门
  • HarmonyOS NEXT仓颉开发语言实现画板案例
  • fish安装node.js环境
  • 【开发杂谈】Auto Caption:使用 Electron 和 Python 开发实时字幕显示软件
  • Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory
  • 车联网网络安全渗透测试:深度解析与实践
  • 商品中心—15.库存分桶扣减的技术文档
  • 一款被我拿来处理图片和视频的免费环保软件
  • Web基础关键_003_CSS(一)
  • 小程序学习笔记:加载效果、上拉加载与节流处理
  • Ubuntu安装Docker部署Python Flask Web应用
  • PHP语法基础篇(六):数组
  • 代码随想录|图论|09沉没孤岛
  • LSTM每个变量的shape分析
  • 从输入到路径:AI赋能的地图语义解析与可视化探索之旅
  • 通过ETL从MySQL同步到GaussDB
  • 喜讯 | Mediatom斩获2025第十三届TopDigital创新营销奖「年度程序化广告平台」殊荣
  • LINUX625 DNS反向解析
  • 基于 Spring Boot + Vue 3的现代化社区团购系统
  • 科技如何影响我们的生活?
  • 工业电子 | 什么是SerDes,为何工业和汽车应用需要它?
  • HarmonyOS NEXT仓颉开发语言实战案例:简约音乐播放页
  • 金蝶云星空客户端自定义控件插件-WPF实现自定义控件
  • 使用Docker部署mysql8
  • 社会工程--如何使用对方的语言
  • JDBC入门:Java连接数据库全指南
  • AI辅助编写前端VUE应用流程
  • 树状dp(dfs)(一道挺基础的)