MyBatis-Plus 使用这么方便,底层是如何处理的呢?

Mybatis-Plus实现思路 本文介绍了一个基于Spring+MyBatis的简化ORM框架实现方案,通过动态代理和反射机制实现SQL自动生成。核心包括:1)定义通用Mapper接口和实体类注解;2)使用反射解析注解生成SQL语句;3)通过JDK动态代理创建Mapper接口代理对象拦截方法调用;4)集成Spring实现自动扫描和注入。该框架实现了类似MyBatis-Plus的基础功能,包括CRUD操作和条件构造器,减少了重复SQL编写工作。 阅读详情

点击上方“芋道源码”,选择“设为星标”

管她前浪,还是后浪?

能浪的浪,才是好浪!

每天 10:33 更新文章,每天掉亿点点头发...

源码精品专栏

 

来源:blog.youkuaiyun.com/weixin_45505313/

article/details/104855453/

504165739c05072fd1c6b6c961b6b220.png


前言

MyBatis-plus是完全基于MyBatis开发的一个增强工具,是在MyBatis的基础上做增强的框架,为简化开发、提高效率而生。

它在MyBatis原本的框架上增加了很多实用性功能,比如乐观锁插件、字段自动填充功能、分页插件、条件构造器、sql 注入器等等。使用 MyBatis-plus 可以完全不写任何 XML 文件,直接使用继承了BaseMapper 接口的类对象完成对数据库的映射操作

基于映射的原理,MyBatis-plus 必然要实现 Mapper中的方法与 SQL 语句的对应转化,以下即为 MyBatis-plus 重要流程图例

999c9b8008acc4d97cfde68de70502e9.png

基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能。

项目地址:https://github.com/YunaiV/ruoyi-vue-pro

1. Mapper 对象方法映射为 SQL 语句

1.在 MyBatis-plus 中, MybatisPlusAutoConfiguration 自动配置类的 sqlSessionFactory()方法为 Spring提供创建 sqlSession的工厂类对象,对 sqlSessionFactory 进行定义的定义类变为了 MybatisSqlSessionFactoryBean。

在 sqlSessionFactory()方法中,除了注入 MyBatis本身的组件,还会注入MyBatis-plus 的 主键生成器、SQL 注入器等组件,最后通过 MybatisSqlSessionFactoryBean#getObject() 方法获取到 sqlSessionFactory 对象

public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
     // TODO 使用 MybatisSqlSessionFactoryBean 而不是 SqlSessionFactoryBean
     MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
     factory.setDataSource(dataSource);
     factory.setVfs(SpringBootVFS.class);
     if (StringUtils.hasText(this.properties.getConfigLocation())) {
         factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
     }
     applyConfiguration(factory);
     if (this.properties.getConfigurationProperties() != null) {
         factory.setConfigurationProperties(this.properties.getConfigurationProperties());
     }
     
    ......
    
     // TODO 自定义枚举包
     if (StringUtils.hasLength(this.properties.getTypeEnumsPackage())) {
         factory.setTypeEnumsPackage(this.properties.getTypeEnumsPackage());
     }
     // TODO 此处必为非 NULL
     GlobalConfig globalConfig = this.properties.getGlobalConfig();
     // TODO 注入填充器
     if (this.applicationContext.getBeanNamesForType(MetaObjectHandler.class,
         false, false).length > 0) {
         MetaObjectHandler metaObjectHandler = this.applicationContext.getBean(MetaObjectHandler.class);
         globalConfig.setMetaObjectHandler(metaObjectHandler);
     }
     // TODO 注入主键生成器
     if (this.applicationContext.getBeanNamesForType(IKeyGenerator.class, false,
         false).length > 0) {
         IKeyGenerator keyGenerator = this.applicationContext.getBean(IKeyGenerator.class);
         globalConfig.getDbConfig().setKeyGenerator(keyGenerator);
     }
     // TODO 注入sql注入器
     if (this.applicationContext.getBeanNamesForType(ISqlInjector.class, false,
         false).length > 0) {
         ISqlInjector iSqlInjector = this.applicationContext.getBean(ISqlInjector.class);
         globalConfig.setSqlInjector(iSqlInjector);
     }
     // TODO 设置 GlobalConfig 到 MybatisSqlSessionFactoryBean
     factory.setGlobalConfig(globalConfig);
     return factory.getObject();
 }

2.MybatisSqlSessionFactoryBean#getObject() 执行懒加载策略,最后通过 buildSqlSessionFactory() 方法创建 SqlSessionFactory 工厂类对象。这个方法的流程很长,不过大致可以分为两个步骤:

  1. 创建 MybatisXMLConfigBuilder 对象,调用其 parse() 方法去解析 XML 配置文件及 Mapper

  2. 解析获得的信息存储在 targetConfiguration 对象中,根据其信息创建 SqlSessionFactory 对象

protected SqlSessionFactory buildSqlSessionFactory() throws Exception {

    final MybatisConfiguration targetConfiguration;

    // TODO 使用 MybatisXmlConfigBuilder 而不是 XMLConfigBuilder
    MybatisXMLConfigBuilder xmlConfigBuilder = null;
    
    ......
    
    } else if (this.configLocation != null) {
        // TODO 使用 MybatisXMLConfigBuilder
        // 1.1 创建 MybatisConfiguration 对象
        xmlConfigBuilder = new MybatisXMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
        // 2.1 将解析获得的信息的引用传递给 targetConfiguration 对象
        targetConfiguration = xmlConfigBuilder.getConfiguration();
    } else {
        LOGGER.debug(() -> "Property 'configuration' or 'configLocation' not specified, using default MyBatis Configuration");
        // TODO 使用 MybatisConfiguration
        targetConfiguration = new MybatisConfiguration();
        Optional.ofNullable(this.configurationProperties).ifPresent(targetConfiguration::setVariables);
    }

    // TODO 无配置启动所必须的
    this.globalConfig = Optional.ofNullable(this.globalConfig).orElseGet(GlobalConfigUtils::defaults);
    this.globalConfig.setDbConfig(Optional.ofNullable(this.globalConfig.getDbConfig()).orElseGet(GlobalConfig.DbConfig::new));

    // TODO 初始化 id-work 以及 打印骚东西
    targetConfiguration.setGlobalConfig(this.globalConfig);
    
    ......
    // 1.2 开始解析 XML 配置文件 及 Mapper 接口
    if (xmlConfigBuilder != null) {
        try {
            xmlConfigBuilder.parse();
            LOGGER.debug(() -> "Parsed configuration file: '" + this.configLocation + "'");
        } catch (Exception ex) {
            throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
        } finally {
            ErrorContext.instance().reset();
        }
    }

    targetConfiguration.setEnvironment(new Environment(MybatisSqlSessionFactoryBean.class.getSimpleName(),
        this.transactionFactory == null ? new SpringManagedTransactionFactory() : this.transactionFactory,
        this.dataSource));

    if (this.mapperLocations != null) {
        if (this.mapperLocations.length == 0) {
            LOGGER.warn(() -> "Property 'mapperLocations' was specified but matching resources are not found.");
        } else {
            for (Resource mapperLocation : this.mapperLocations) {
                if (mapperLocation == null) {
                    continue;
                }
                try {
                    XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
                        targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments());
                    xmlMapperBuilder.parse();
                } catch (Exception e) {
                    throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
                } finally {
                    ErrorContext.instance().reset();
                }
                LOGGER.debug(() -> "Parsed mapper file: '" + mapperLocation + "'");
            }
        }
    } else {
        LOGGER.debug(() -> "Property 'mapperLocations' was not specified.");
    }

    // 2.2 根据 targetConfiguration 对象中保存的信息创建 SqlSessionFactory 对象
    final SqlSessionFactory sqlSessionFactory = new MybatisSqlSessionFactoryBuilder().build(targetConfiguration);
    
     ......

    return sqlSessionFactory;
}

3.MybatisXMLConfigBuilder#parse() 会去解析配置文件,最后会调用到其内部方法 mapperElement()。这个方法完成解析 Mapper工作,并将其添加到配置类 MybatisConfiguration 中

private void mapperElement(XNode parent) throws Exception {
   /*
    * 定义集合 用来分类放置mybatis的Mapper与XML 按顺序依次遍历
    */
   if (parent != null) {
       //指定在classpath中的mapper文件
       Set<String> resources = new HashSet<>();
       //指向一个mapper接口
       Set<Class<?>> mapperClasses = new HashSet<>();
       setResource(parent, resources, mapperClasses);
       // 依次遍历 首先 resource 然后 mapper
       for (String resource : resources) {
           ErrorContext.instance().resource(resource);
           InputStream inputStream = Resources.getResourceAsStream(resource);
           //TODO
           XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource,
               configuration.getSqlFragments());
           mapperParser.parse();
       }
       for (Class<?> mapper : mapperClasses) {
           // 主要关注此处
           configuration.addMapper(mapper);
       }
   }
}

4.MybatisConfiguration#addMapper()方法其实是去调用 MybatisMapperRegistry#addMapper() 方法,其核心是MybatisMapperAnnotationBuilder#parse()

public <T> void addMapper(Class<T> type) {
     if (type.isInterface()) {
         if (hasMapper(type)) {
             // TODO 如果之前注入 直接返回
             return;
             // TODO 这里就不抛异常了
//                throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
         }
         boolean loadCompleted = false;
         try {
             // TODO 这里也换成 MybatisMapperProxyFactory 而不是 MapperProxyFactory
             knownMappers.put(type, new MybatisMapperProxyFactory<>(type));
             // It's important that the type is added before the parser is run
             // otherwise the binding may automatically be attempted by the
             // mapper parser. If the type is already known, it won't try.
             // TODO 这里也换成 MybatisMapperAnnotationBuilder 而不是 MapperAnnotationBuilder
             MybatisMapperAnnotationBuilder parser = new MybatisMapperAnnotationBuilder(config, type);
             parser.parse();
             loadCompleted = true;
         } finally {
             if (!loadCompleted) {
                 knownMappers.remove(type);
             }
         }
     }
 }

5.MybatisMapperAnnotationBuilder#parse() 方法真正开始完成 Mapper 接口中的方法与 SQL 语句的映射,其中 parseStatement()方法是解析 @Select/@Update 等注解写入的 SQL语句,而代码 GlobalConfigUtils.getSqlInjector(configuration).inspectInject(assistant, type) 通过 MaBatis-plus的 SQL 注入器完成 Mapper 方法与 SQL 语句的转化

@Override
 public void parse() {
     String resource = type.toString();
     if (!configuration.isResourceLoaded(resource)) {
         loadXmlResource();
         configuration.addLoadedResource(resource);
         final String typeName = type.getName();
         assistant.setCurrentNamespace(typeName);
         parseCache();
         parseCacheRef();
         SqlParserHelper.initSqlParserInfoCache(type);
         Method[] methods = type.getMethods();
         for (Method method : methods) {
             try {
                 // issue #237
                 if (!method.isBridge()) {
                 // 解析 @Select 注解写入的 SQL
                     parseStatement(method);
                     SqlParserHelper.initSqlParserInfoCache(typeName, method);
                 }
             } catch (IncompleteElementException e) {
                 // TODO 使用 MybatisMethodResolver 而不是 MethodResolver
                 configuration.addIncompleteMethod(new MybatisMethodResolver(this, method));
             }
         }
         // TODO 注入 CURD 动态 SQL , 放在在最后, because 可能会有人会用注解重写sql
         if (GlobalConfigUtils.isSupperMapperChildren(configuration, type)) {
             GlobalConfigUtils.getSqlInjector(configuration).inspectInject(assistant, type);
         }
     }
     parsePendingMethods();
 }

6.AbstractSqlInjector#inspectInject() 会完成 BaseMapper 接口中提供的通用方法对应的 SQL 语句准备,这部分主要通过 AbstractMethod#inject()方法完成

@Override
 public void inspectInject(MapperBuilderAssistant builderAssistant, Class<?> mapperClass) {
     Class<?> modelClass = extractModelClass(mapperClass);
     if (modelClass != null) {
         String className = mapperClass.toString();
         Set<String> mapperRegistryCache = GlobalConfigUtils.getMapperRegistryCache(builderAssistant.getConfiguration());
         if (!mapperRegistryCache.contains(className)) {
             List<AbstractMethod> methodList = this.getMethodList(mapperClass);
             if (CollectionUtils.isNotEmpty(methodList)) {
                 TableInfo tableInfo = TableInfoHelper.initTableInfo(builderAssistant, modelClass);
                 // 循环注入自定义方法
                 methodList.forEach(m -> m.inject(builderAssistant, mapperClass, modelClass, tableInfo));
             } else {
                 logger.debug(mapperClass.toString() + ", No effective injection method was found.");
             }
             mapperRegistryCache.add(className);
         }
     }
 }

7.AbstractMethod#inject()方法并没有什么特别的操作,只是调用其子类实现 injectMappedStatement()方法。以 SelectOne#injectMappedStatement() 为例,其 SQL 语句的核心在于 SqlMethod 类,这个枚举类中缓存了可以动态拼接的 SQL 语句脚本,只需要填上参数 format 就可以得到 SQL 语句的执行脚本。

以上过程结束,只需要将所有信息通过 addInsertMappedStatement()方法封装成 MappedStatement对象并将其加入到容器中,这样 Mapper接口方法调用时,就可以通过 动态代理 的方式找到其对应执行的 SQL 脚本,至此 SQL 语句准备及配置解析就完成了。

最后拼接的 SQL 语句 脚本形式如下示例,实际执行数据库操作时会解析这个脚本完成变量替换,从而得到可执行的 SQL 语句

<script>
 <choose>
     <when test="ew != null and ew.sqlFirst != null">
         ${ew.sqlFirst}
     </when>
     <otherwise></otherwise>
 </choose>
 SELECT
 <choose>
     <when test="ew != null and ew.sqlSelect != null">
         ${ew.sqlSelect}
     </when>
     <otherwise>id,name,type</otherwise>
 </choose>
 FROM node
 <if test="ew != null">
     <where>
         <if test="ew.entity != null">
             <if test="ew.entity.id != null">id=#{ew.entity.id}</if>
             <if test="ew.entity['name'] != null">AND name=#{ew.entity.name}</if>
             <if test="ew.entity['type'] != null">AND type=#{ew.entity.type}</if>
         </if>
         <if test="ew.sqlSegment != null and ew.sqlSegment != '' and ew.nonEmptyOfWhere">
             <if test="ew.nonEmptyOfEntity and ew.nonEmptyOfNormal">AND</if>
             ${ew.sqlSegment}
         </if>
     </where>
     <if test="ew.sqlSegment != null and ew.sqlSegment != '' and ew.emptyOfWhere">
         ${ew.sqlSegment}
     </if>
 </if>
 <choose>
     <when test="ew != null and ew.sqlComment != null">
         ${ew.sqlComment}
     </when>
     <otherwise></otherwise>
 </choose>
</script>
 @Override
 public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
     SqlMethod sqlMethod = SqlMethod.SELECT_ONE;
     SqlSource sqlSource = languageDriver.createSqlSource(configuration, String.format(sqlMethod.getSql(),
         sqlFirst(), sqlSelectColumns(tableInfo, true), tableInfo.getTableName(),
         sqlWhereEntityWrapper(true, tableInfo), sqlComment()), modelClass);
     return this.addSelectMappedStatementForTable(mapperClass, getMethod(sqlMethod), sqlSource, tableInfo);
 }

8.SqlSessionFactory对象的创建需要回到 MybatisSqlSessionFactoryBean#buildSqlSessionFactory()方法中,很容易追踪到 MybatisSqlSessionFactoryBuilder#build()方法,最后其实是通过 SqlSessionFactoryBuilder#build()方法创建了一个 DefaultSqlSessionFactory 对象返回

public SqlSessionFactory build(Configuration config) {
 return new DefaultSqlSessionFactory(config);
}

基于微服务的思想,构建在 B2C 电商场景下的项目实战。核心技术栈,是 Spring Boot + Dubbo 。未来,会重构成 Spring Cloud Alibaba 。

项目地址:https://github.com/YunaiV/onemall

2. Mapper 操作数据库的流程

1.@MapperScan 注解通过 @Import(MapperScannerRegistrar.class) 引入扫描注册的类MapperScannerRegistrar,该类实现了ImportBeanDefinitionRegistrar接口并重写registerBeanDefinitions()方法,在该方法中注册了 MapperScannerConfigurer 类

void registerBeanDefinitions(AnnotationAttributes annoAttrs, BeanDefinitionRegistry registry, String beanName) {

 BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);

 ......

 registry.registerBeanDefinition(beanName, builder.getBeanDefinition());
}

2.MapperScannerConfigurer 是 Mapper接口的扫描配置类,实现了 BeanDefinitionRegistryPostProcessor 接口,其 postProcessBeanDefinitionRegistry()方法会在容器启动过程中被回调,通过 ClassPathMapperScanner#scan()方法完成 Mapper 的扫描注册

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
if (this.processPropertyPlaceHolders) {
  processPropertyPlaceHolders();
}

ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
scanner.setAddToConfig(this.addToConfig);
scanner.setAnnotationClass(this.annotationClass);
scanner.setMarkerInterface(this.markerInterface);
scanner.setSqlSessionFactory(this.sqlSessionFactory);
scanner.setSqlSessionTemplate(this.sqlSessionTemplate);
scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);
scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);
scanner.setResourceLoader(this.applicationContext);
scanner.setBeanNameGenerator(this.nameGenerator);
scanner.setMapperFactoryBeanClass(this.mapperFactoryBeanClass);
if (StringUtils.hasText(lazyInitialization)) {
  scanner.setLazyInitialization(Boolean.valueOf(lazyInitialization));
}
scanner.registerFilters();
scanner.scan(
    StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
}

3.ClassPathMapperScanner#processBeanDefinitions() 将扫描到的 Mapper接口生成的对应 BeanDefinition 的 beanClass 属性替换为 MapperFactoryBean,这样每次获取 Mapper 实例实际是通过 MapperFactoryBean 的实例去获取

此处体现了 FactoryBean 的定位,即用于获取同一类 bean 的工厂 bean

private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
 GenericBeanDefinition definition;
 for (BeanDefinitionHolder holder : beanDefinitions) {
   definition = (GenericBeanDefinition) holder.getBeanDefinition();
   String beanClassName = definition.getBeanClassName();
   LOGGER.debug(() -> "Creating MapperFactoryBean with name '" + holder.getBeanName() + "' and '" + beanClassName
       + "' mapperInterface");

   // the mapper interface is the original class of the bean
   // but, the actual class of the bean is MapperFactoryBean
   definition.getConstructorArgumentValues().addGenericArgumentValue(beanClassName); // issue #59
   definition.setBeanClass(this.mapperFactoryBeanClass);

   definition.getPropertyValues().add("addToConfig", this.addToConfig);

   boolean explicitFactoryUsed = false;
   if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {
     definition.getPropertyValues().add("sqlSessionFactory",
         new RuntimeBeanReference(this.sqlSessionFactoryBeanName));
     explicitFactoryUsed = true;
   } else if (this.sqlSessionFactory != null) {
     definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory);
     explicitFactoryUsed = true;
   }

   if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {
     if (explicitFactoryUsed) {
       LOGGER.warn(
           () -> "Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
     }
     definition.getPropertyValues().add("sqlSessionTemplate",
         new RuntimeBeanReference(this.sqlSessionTemplateBeanName));
     explicitFactoryUsed = true;
   } else if (this.sqlSessionTemplate != null) {
     if (explicitFactoryUsed) {
       LOGGER.warn(
           () -> "Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
     }
     definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate);
     explicitFactoryUsed = true;
   }

   if (!explicitFactoryUsed) {
     LOGGER.debug(() -> "Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");
     definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
   }
   definition.setLazyInit(lazyInitialization);
 }
}

4.@Autowired 自动注入 Mapper 触发容器获取 bean 的方法,调用到 MapperFactoryBean#getObject()方法,最终调用到 sqlSessionTemplate#getMapper()方法

@Override
public <T> T getMapper(Class<T> type) {
    return getConfiguration().getMapper(type, this);
}

5.MyBatis-plus 使用的配置类是MybatisConfiguration,最终调用到 MybatisMapperRegistry#getMapper()方法,这里就进入了动态代理获取 MapperProxy 实例的流程

@Override
 public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
     // TODO 这里换成 MybatisMapperProxyFactory 而不是 MapperProxyFactory
     final MybatisMapperProxyFactory<T> mapperProxyFactory = (MybatisMapperProxyFactory<T>) knownMappers.get(type);
     if (mapperProxyFactory == null) {
         throw new BindingException("Type " + type + " is not known to the MybatisPlusMapperRegistry.");
     }
     try {
         return mapperProxyFactory.newInstance(sqlSession);
     } catch (Exception e) {
         throw new BindingException("Error getting mapper instance. Cause: " + e, e);
     }
 }

6.MybatisMapperProxyFactory#newInstance()方法给自动注入返回一个 MybatisMapperProxy 代理对象

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

7.调用 Mapper 接口的方法触发代理对象的 MybatisMapperProxy#invoke(),此时根据 Mapper 对象被调用的方法生成 MybatisMapperMethod 对象,通过MybatisMapperMethod#execute()去真正地执行 SQL 语句,从而完成数据库操作。

@Override
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
     try {
         if (Object.class.equals(method.getDeclaringClass())) {
             return method.invoke(this, args);
         } else if (method.isDefault()) {
             return invokeDefaultMethod(proxy, method, args);
         }
     } catch (Throwable t) {
         throw ExceptionUtil.unwrapThrowable(t);
     }
     final MybatisMapperMethod mapperMethod = cachedMapperMethod(method);
     return mapperMethod.execute(sqlSession, args);
 }


欢迎加入我的知识星球,一起探讨架构,交流源码。加入方式,长按下方二维码噢:

b6c1ac06b69aee1da09090aab09c7b78.png

已在知识星球更新源码解析如下:

6f4e7221d1d4993f2c0cb0bff05978a1.png

5cd0ac0df1bbe13012aea10e6c55ea2c.png

afa876550654746e10be19d92338f1ec.png

b31e9831889324c70333ae3ea1fefe51.png

最近更新《芋道 SpringBoot 2.X 入门》系列,已经 101 余篇,覆盖了 MyBatis、Redis、MongoDB、ES、分库分表、读写分离、SpringMVC、Webflux、权限、WebSocket、Dubbo、RabbitMQ、RocketMQ、Kafka、性能测试等等内容。

提供近 3W 行代码的 SpringBoot 示例,以及超 4W 行代码的电商微服务项目。

获取方式:点“在看”,关注公众号并回复 666 领取,更多内容陆续奉上。

文章有帮助的话,在看,转发吧。
谢谢支持哟 (*^__^*)
mybatis-plus集成dm,分页插件不生效 一、问题产生集成dm,兼容kingbase后,切换数据源dm,发现分页插件不生效二、问题分析通过查看源码,发现MyBatis-Plus分页插件通过属性确定数据库类型,动态生成符合目标数据库的分页语法。其底层实现依赖以下核心机制:‌‌插件内部维护静态注册表,存储所有支持的数据库类型(如DbType.DM)与对应IDialect接口实现的映射关系‌。‌‌分页拦截器(如)通过从注册表获取IDialect实例,调用其方法对原始SQL进行分页语法改造‌。 阅读详情

相关推荐

mybatis-plus 实践及架构原理

mybatis-plus 实践及架构原理,mybatis-plus 实践及架构原理

mybatis之mapper

意义 用于映射数据库RUID操作,将SQL语句和Java接口进行绑定 基于XML方式映射SQL 定义XML SQL配置文件 StudentMapper.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" ...

逐墨飞扬的博客 2253

Oracle入门——基础语法篇

ROWID是Oracle中的一个伪列,用于唯一标识数据库中的每一行。在查询中,可以使用ROWID来定位和操作特定的行,例如,删除特定的行或更新特定的行。在Oracle中,子查询是指嵌套在另一个查询内部的查询语句,它可以作为主查询的一部分,用于提供额外的过滤条件、计算或数据源。在Oracle中,连接查询是通过使用JOIN子句将两个或多个表中的数据合并在一起,以获取满足特定条件的结果集。在Oracle数据库中,ROWID和ROWNUM都是用于对行进行标识和定位的伪列,它们在查询中的使用有一些不同之处。

麦当当的博客 3091

mybatisplus生成的mapper和bean,后置处理器实现根据bean获取mapper

实现根据bean获取mapper

Rae_C的博客 936

AI Agent实战:WorkBuddy安装部署、任务执行与模型接入全教程

AI Agent是当前自动化办公与智能工作流的核心技术,它区别于传统问答式AI,能够理解目标、拆解任务并调用工具交付完整成果。其底层原理基于任务规划、工具调用与结果验证的循环机制,让机器从“提供建议”进化为“完成任务”。在工程实践中,合理配置模型服务(如接入DeepSeek)、设计标准化Skill(技能包)与自定义指令,可以显著提升Agent在报告生成、数据分析、竞品调研等场景中的稳定性与效率。WorkBuddy作为典型的任务式AI工作台,为运营、产品、开发等多角色提供了统一入口,覆盖安装部署、任务描述公式

weixin_26712075的博客 293

LDO稳定性分析

根据补偿方式和拓扑结构的不同,三个极点之间的相互位置有可能发生变化,但 是 LDO 通常采用较大的输出电容 Cout,以及较大的调整管也会导致较大的 Cpar, 所以 p1、p2 通常位于较低的频率处,而 p3 和 z1 则由于 Resr较小会位于较高的频 率处。不过幸运的是,对于较大的 Cout来说,只要选择合适的 Resr,就可以将左半平面零点 Z1 的频率降低,甚至使 Z1 进入单位增益带宽内,左半平面零点的进入将对相位有所改善,这不仅可以消除振荡的风险,还可以在单位增益频率处得到较好的相位裕度。

模拟芯片设计 1595

Mybatis配置 mapper

mybatis之mapper配置

瓜大师的博客 3314

杰理SDK入门教程(五):按键使用配置

摘要 杰理SDK提供IO按键和AD按键两种方案。IO按键通过GPIO电平检测实现,配置时需要设置板级宏定义和硬件连接,默认使用PB1引脚。AD按键基于ADC电压采样,通过电阻分压区分按键,需配置功能使能、硬件通道和键值适配。按键功能通过修改SDK中的key_table文件实现。两种方案适用于不同硬件场景,开发者可根据需求选择。

qq_42014563的博客 778

MyBatis-Plus 使用这么方便,底层源码是如何处理的呢?

文章目录Mapper 对象方法映射为 SQL 语句Mapper 操作数据库的流程前言MyBatis-plus是完全基于MyBatis开发的一个增强工具,是在MyBatis的基础上做增强的框架,为简化开发、提高效率而生。它在MyBatis原本的框架上增加了很多实用性功能,比如乐观锁插件、字段自动填充功能、分页插件、条件构造器、sql 注入器等等。使用 MyBatis-plu...

Java精选 305

2025年华为杯中国研究生数学建模竞赛E题 高速列车轴承智能故障诊断问题 思路+代码

all_data, file_info = preprocessor.load_mat_files(file_list[:50]) # 加载前50个文件作为示例。[y_source, y_source, domain_labels], # 注意:这里使用伪标签。X_target = np.random.randn(100, X_source.shape[1], 1) # 示例数据。"""构建CNN-Transformer混合模型""""""构建Transformer模型"""

YOLO 1048

得物(毒)App潮鞋价格波动监控系统实战:从爬虫开发到数据可视化完整指南

本文将带领您从零开始构建一套完整的得物潮鞋价格监控系统,涵盖爬虫开发、数据存储、价格波动分析和可视化展示等全流程技术。我们将使用最新的Python技术栈,包括异步爬虫框架、智能代理池、反爬虫绕过技巧,以及基于机器学习的时间序列预测模型。无论您是想要追踪特定鞋款价格的潮流爱好者,还是希望构建商业级监控系统的开发者,这篇文章都将为您提供切实可行的解决方案。

2201_76125261的博客 2509

MyBatis-Plus流式查询深度解析:高效处理百万级数据的实战指南

流式查询(Streaming Query)是一种逐条获取查询结果的数据库访问模式。与传统查询方式相比,它不会一次性将所有结果加载到内存中,而是通过游标(Cursor)逐条处理。核心价值🚀 突破内存限制处理海量数据⚙️ 与MyBatis-Plus无缝集成🔧 通过fetchSize精细控制性能最佳实践始终在事务中使用使用try-with-resources确保关闭根据网络环境调整fetchSize避免在流式查询中执行复杂操作。

xiaoyu❅的博客 2181

蓝牙攻防实战指南:低功耗蓝牙

Bluetooth Low Energy(也称Bluetooth Smart)是经典蓝牙(Bluetooth Classic)的演进版本,设计目标是实现极低功耗,适用于无需频繁更换电池的设备,如智能手环、健康监测器、蓝牙标签等。Bluetooth Low Energy 是一项极具前景的无线通信技术,它以极低的功耗实现了短距离高效通信,广泛应用于智能设备和物联网领域。然而,其简化的协议结构和配对机制也带来了不小的安全挑战。

idlecloud0105的博客 683

Mybatis plus源码浅谈--com.baomidou.mybatisplus.extension包

正文 在com.baomidou.mybatisplus.extension包的Model类中, 有这样一行注释 也就说明,使用Mybatis plus的前提,必须得让原Mapper继承baseMapper才有使用的可能,所以先加上吧 在其中有大量类似sqlSession.insert(sqlStatement(SqlMethod.INSERT_ONE),this)的方法 点进SqlMethod.INSERT_ONE方法中, 可以看到大量写好的,SQL语句,那么也就是说,Mybatis Plus一开

weixin_40598838的博客 2万+

用一张分析型 CDS Query 看清争议案件新增与结案节奏:C_OpenClosedDisputeCase 深度解读

应收账款争议管理中的关键CDS视图分析 摘要:C_OpenClosedDisputeCase是SAP系统中用于监控应收账款争议案件的重要CDS视图,提供三个时间窗口(当日、近5天、当月)的新增与结案数据。该视图通过"创建vs解决"的净变化指标,帮助财务团队实时掌握争议管理趋势,特别适用于多币种跨国企业的现金流管理。其核心价值在于将争议管理从被动"救火"转变为可量化运营,通过统一汇率换算和关键日期参数,为管理层提供标准化的运营仪表盘。视图采用特权访问模式,需通过上层应用

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 124

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

为啥:使用mybatis-plus的批量插入接口特别慢?

本人Java实习生,做项目时遇到困难如题。团队项目代码用的是mybatis-plus的IService接口的saveBatch方法,但速度特别慢。 我在网上搜关于saveBatch的资料,很少,只知道batchSize是分批处理时一次性处理的数据条数,它的本质是为了让开发者选取一个小于数据库支持的size值,以便碰到异常时可以针对提交的数据进行回滚。 下图是我项目运行时插入的数据条...

liuji0517的博客 4236

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

使用mybatis-plus查询列表,如果查询不到数据,会返回[],而不是null的源码探讨

首先从源码中看出,mybatis-plus查询列表selectList()是调用 org.apache.ibatis.session.SqlSession 包下的selectList()方法。 找到ibatis中DefaultSqlSession中的selectList()方法 一直往下找,直到DefaultResultSetHandler类,可以看到handleResultSets()方法最终返回的是 multipleResults final List multipleResults =.

qq_34486648的博客 4379

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

<后端日记> mybatis-plus日志输出

然而mybatis的这部分日志输出没有按照统一的pattern来,导致有很多日志被处理成了多行,会影响到日志的采集,类似这种。主要是因为我们的additivity设置了true,会导致继承了root以后,打印了两次,改为false即可。到这里相信小伙伴们明白了,对于不同的日志impl,底层其实会走不同的处理handler。经过这一阵的工作,已经把项目的基础设置完成的差不多了,接下来就是做集群的日志管理了。需要修改日志的初衷在于,我们要做集群日志,需要统一日志的pattern。

工业 AI 工程手记 1058

MyBatis-Plus 性能优化:批量操作与动态 SQL 的底层原理

批处理本质利用 JDBC 的addBatch()事务原子性:通过commit()统一提交动态 SQL 本质运行时生成 AST (抽象语法树)预编译防注入:所有参数转为参数执行效率公式总耗时 $T = T_{parse} + N \times T_{exec}$$T_{parse}$:SQL 解析时间$N$:操作次数$T_{exec}$:单次执行时间通过批处理降低 $N$ 值,通过动态 SQL 减少 $T_{parse}$ 开销,实现双重性能提升。

qqquxgsjdgxjkwh的博客 356

Mybatis-plus中的接口(BaseMapper<T> 和 IService<T>)

绝大多数时候:在你的 Controller 或 ServiceImpl 里,直接调用 IService 的方法(如 userService.saveBatch())。因为它功能更强,代码更简洁。特殊情况:如果你在写非常底层的逻辑,或者不想引入 Service 层,才直接去调用 BaseMapper。BaseMapper:你要自己写循环去插 1000 条数据。IService:你直接把 1000 条数据的 List 扔给它,它帮你搞定。

2403_88484791的博客 913
上一篇: Elasticsearch 实现分页的 3 种方式,还有谁不会??
下一篇: 到底要不要去外包公司?这篇带你全面了解外包那些坑!
公众号-芋道源码
博客等级 码龄10年 1639粉丝 377原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值