百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

Mybatis Plus 批量插入这样操作提升性能

ztj100 2025-01-07 17:23 21 浏览 0 评论

使用的mybatisplus的批量插入方法:saveBatch(),之前就看到过网上都在说在jdbc的url路径上加上rewriteBatchedStatements=true 参数mysql底层才能开启真正的批量插入模式。

保证5.1.13以上版本的驱动,才能实现高性能的批量插入。MySQL JDBC驱动在默认情况下会无视executeBatch()语句,把我们期望批量执行的一组sql语句拆散,一条一条地发给MySQL数据库,批量插入实际上是单条插入,直接造成较低的性能。只有把rewriteBatchedStatements参数置为true, 驱动才会帮你批量执行SQL。另外这个选项对INSERT/UPDATE/DELETE都有效。

目前我的数据表目前是没有建立索引的,即使是在1000来w的数据量下进行1500条的批量插入也不可能消耗20来秒吧,于是矛盾转移到saveBatch方法,使用版本:

查看源码:

public boolean saveBatch(Collection<T> entityList, int batchSize) {     String sqlStatement = this.getSqlStatement(SqlMethod.INSERT_ONE);     return this.executeBatch(entityList, batchSize, (sqlSession, entity) -> {         sqlSession.insert(sqlStatement, entity);     }); }
protected <E> boolean executeBatch(Collection<E> list, int batchSize, BiConsumer<SqlSession, E> consumer) {        return SqlHelper.executeBatch(this.entityClass, this.log, list, batchSize, consumer);    }
public static <E> boolean executeBatch(Class<?> entityClass, Log log, Collection<E> list, int batchSize, BiConsumer<SqlSession, E> consumer) {    Assert.isFalse(batchSize < 1, "batchSize must not be less than one", new Object[0]);    return !CollectionUtils.isEmpty(list) && executeBatch(entityClass, log, (sqlSession) -> {        int size = list.size();        int i = 1;        for(Iterator var6 = list.iterator(); var6.hasNext(); ++i) {            E element = var6.next();            consumer.accept(sqlSession, element);            if (i % batchSize == 0 || i == size) {                sqlSession.flushStatements();            }        }    });}

最终来到了executeBatch()方法,可以看到这很明显是在一条一条循环插入,通过sqlSession.flushStatements()将一个个单条插入的insert语句分批次进行提交,而且是同一个sqlSession,这相比遍历集合循环insert来说有一定的性能提升,但是这并不是sql层面真正的批量插入。

通过查阅相关文档后,发现mybatisPlus提供了sql注入器,我们可以自定义方法来满足业务的实际开发需求。

sql注入器官网

https://baomidou.com/pages/42ea4a/

sql注入器官方示例

https://gitee.com/baomidou/mybatis-plus-samples/tree/master/mybatis-plus-sample-deluxe

在mybtisPlus的核心包下提供的默认可注入方法有这些:

在扩展包下,mybatisPlus还为我们提供了可扩展的可注入方法:

  • AlwaysUpdateSomeColumnById:根据Id更新每一个字段,全量更新不忽略null字段,解决mybatis-plus中updateById默认会自动忽略实体中null值字段不去更新的问题;
  • InsertBatchSomeColumn:真实批量插入,通过单SQL的insert语句实现批量插入;
  • Upsert:更新or插入,根据唯一约束判断是执行更新还是删除,相当于提供insert on duplicate key update支持。

可以发现mybatisPlus已经提供好了InsertBatchSomeColumn的方法,我们只需要把这个方法添加进我们的sql注入器即可。

public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {    KeyGenerator keyGenerator = NoKeyGenerator.INSTANCE;    SqlMethod sqlMethod = SqlMethod.INSERT_ONE;    List<TableFieldInfo> fieldList = tableInfo.getFieldList();    String insertSqlColumn = tableInfo.getKeyInsertSqlColumn(true, false) + this.filterTableFieldInfo(fieldList, this.predicate, TableFieldInfo::getInsertSqlColumn, "");    //------------------------------------拼接批量插入语句----------------------------------------    String columnScript = "(" + insertSqlColumn.substring(0, insertSqlColumn.length() - 1) + ")";    String insertSqlProperty = tableInfo.getKeyInsertSqlProperty(true, "et.", false) + this.filterTableFieldInfo(fieldList, this.predicate, (i) -> {        return i.getInsertSqlProperty("et.");    }, "");    insertSqlProperty = "(" + insertSqlProperty.substring(0, insertSqlProperty.length() - 1) + ")";    String valuesScript = SqlScriptUtils.convertForeach(insertSqlProperty, "list", (String)null, "et", ",");    //------------------------------------------------------------------------------------------    String keyProperty = null;    String keyColumn = null;    if (tableInfo.havePK()) {        if (tableInfo.getIdType() == IdType.AUTO) {            keyGenerator = Jdbc3KeyGenerator.INSTANCE;            keyProperty = tableInfo.getKeyProperty();            keyColumn = tableInfo.getKeyColumn();        } else if (null != tableInfo.getKeySequence()) {            keyGenerator = TableInfoHelper.genKeyGenerator(this.getMethod(sqlMethod), tableInfo, this.builderAssistant);            keyProperty = tableInfo.getKeyProperty();            keyColumn = tableInfo.getKeyColumn();        }    }    String sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), columnScript, valuesScript);    SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, modelClass);    return this.addInsertMappedStatement(mapperClass, modelClass, this.getMethod(sqlMethod), sqlSource, (KeyGenerator)keyGenerator, keyProperty, keyColumn);}

接下来就通过SQL注入器实现真正的批量插入

默认的sql注入器

public class DefaultSqlInjector extends AbstractSqlInjector {    public DefaultSqlInjector() {    }    public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {        if (tableInfo.havePK()) {            return (List)Stream.of(new Insert(), new Delete(), new DeleteByMap(), new DeleteById(), new DeleteBatchByIds(), new Update(), new UpdateById(), new SelectById(), new SelectBatchByIds(), new SelectByMap(), new SelectCount(), new SelectMaps(), new SelectMapsPage(), new SelectObjs(), new SelectList(), new SelectPage()).collect(Collectors.toList());        } else {            this.logger.warn(String.format("%s ,Not found @TableId annotation, Cannot use Mybatis-Plus 'xxById' Method.", tableInfo.getEntityType()));            return (List)Stream.of(new Insert(), new Delete(), new DeleteByMap(), new Update(), new SelectByMap(), new SelectCount(), new SelectMaps(), new SelectMapsPage(), new SelectObjs(), new SelectList(), new SelectPage()).collect(Collectors.toList());        }    }}

继承DefaultSqlInjector自定义sql注入器

/** * @author zhmsky * @date 2022/8/15 15:13 */public class MySqlInjector extends DefaultSqlInjector {    @Override    public List<AbstractMethod> getMethodList(Class<?> mapperClass) {        List<AbstractMethod> methodList = super.getMethodList(mapperClass);        //更新时自动填充的字段,不用插入值        methodList.add(new InsertBatchSomeColumn(i -> i.getFieldFill() != FieldFill.UPDATE));        return methodList;    }}

将自定义的sql注入器注入到Mybatis容器中

/** * @author zhmsky * @date 2022/8/15 15:15 */@Configurationpublic class MybatisPlusConfig {    @Bean    public MySqlInjector sqlInjector() {        return new MySqlInjector();    }}

继承BaseMapper添加自定义方法

/** * @author zhmsky * @date 2022/8/15 15:17 */public interface CommonMapper<T> extends BaseMapper<T> {    /**     * 真正的批量插入     * @param entityList     * @return     */    int insertBatchSomeColumn(List<T> entityList);}

对应的mapper层接口继承上面自定义的mapper

/* * @author zhmsky * @since 2021-12-01 */@Mapperpublic interface UserMapper extends CommonMapper<User> {}

最后直接调用UserMapper的insertBatchSomeColumn()方法即可实现真正的批量插入。

@Testvoid contextLoads() {    for (int i = 0; i < 5; i++) {        User user = new User();        user.setAge(10);        user.setUsername("zhmsky");        user.setEmail("21575559@qq.com");        userList.add(user);    }    long l = System.currentTimeMillis();    userMapper.insertBatchSomeColumn(userList);    long l1 = System.currentTimeMillis();    System.out.println("-------------------:"+(l1-l));    userList.clear();}

查看日志输出信息,观察执行的sql语句;

发现这才是真正意义上的sql层面的批量插入。

但是,到这里并没有结束,mybatisPlus官方提供的insertBatchSomeColumn方法不支持分批插入,也就是有多少直接全部一次性插入,这就可能会导致最后的sql拼接语句特别长,超出了mysql的限制,于是我们还要实现一个类似于saveBatch的分批的批量插入方法。

添加分批插入

模仿原来的saveBatch方法:

 * @author zhmsky * @since 2021-12-01 */@Servicepublic class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {    @Override    @Transactional(rollbackFor = {Exception.class})    public boolean saveBatch(Collection<User> entityList, int batchSize) {        try {            int size = entityList.size();            int idxLimit = Math.min(batchSize, size);            int i = 1;            //保存单批提交的数据集合            List<User> oneBatchList = new ArrayList<>();            for (Iterator<User> var7 = entityList.iterator(); var7.hasNext(); ++i) {                User element = var7.next();                oneBatchList.add(element);                if (i == idxLimit) {                    baseMapper.insertBatchSomeColumn(oneBatchList);                    //每次提交后需要清空集合数据                    oneBatchList.clear();                    idxLimit = Math.min(idxLimit + batchSize, size);                }            }        } catch (Exception e) {            log.error("saveBatch fail", e);            return false;        }        return true;    }}

测试:

@Testvoid contextLoads() {    for (int i = 0; i < 20; i++) {        User user = new User();        user.setAge(10);        user.setUsername("zhmsky");        user.setEmail("21575559@qq.com");        userList.add(user);    }    long l = System.currentTimeMillis();    userService.saveBatch(userList,10);    long l1 = System.currentTimeMillis();    System.out.println("-------------------:"+(l1-l));    userList.clear();}

输出结果:

分批插入已满足,到此收工结束了。

接下来最重要的测试下性能

当前数据表的数据量在100w多条,在此基础上分别拿原始的saveBatch(假的批量插入)和 insertBatchSomeColumn(真正的批量插入)进行性能对比----(jdbc均开启rewriteBatchedStatements):

原来的假的批量插入:

@Test  void insert(){      for (int i = 0; i < 50000; i++) {          User user = new User();      

自定义的insertBatchSomeColumn:

@Testvoid contextLoads() {    for (int i = 0; i < 50000; i++) {        User user = new User

分批插入5w条数据,自定义的真正意义上的批量插入耗时减少了3秒左右,用insertBatchSomeColum分批插入1500条数据耗时650毫秒,这速度已经挺快了

相关推荐

Vue 技术栈(全家桶)(vue technology)

Vue技术栈(全家桶)尚硅谷前端研究院第1章:Vue核心Vue简介官网英文官网:https://vuejs.org/中文官网:https://cn.vuejs.org/...

vue 基础- nextTick 的使用场景(vue的nexttick这个方法有什么用)

前言《vue基础》系列是再次回炉vue记的笔记,除了官网那部分知识点外,还会加入自己的一些理解。(里面会有部分和官网相同的文案,有经验的同学择感兴趣的阅读)在开发时,是不是遇到过这样的场景,响应...

vue3 组件初始化流程(vue组件初始化顺序)

学习完成响应式系统后,咋们来看看vue3组件的初始化流程既然是看vue组件的初始化流程,咋们先来创建基本的代码,跑跑流程(在app.vue中写入以下内容,来跑流程)...

vue3优雅的设置element-plus的table自动滚动到底部

场景我是需要在table最后添加一行数据,然后把滚动条滚动到最后。查网上的解决方案都是读取html结构,暴力的去获取,虽能解决问题,但是不喜欢这种打补丁的解决方案,我想着官方应该有相关的定义,于是就去...

Vue3为什么推荐使用ref而不是reactive

为什么推荐使用ref而不是reactivereactive本身具有很大局限性导致使用过程需要额外注意,如果忽视这些问题将对开发造成不小的麻烦;ref更像是vue2时代optionapi的data的替...

9、echarts 在 vue 中怎么引用?(必会)

首先我们初始化一个vue项目,执行vueinitwebpackechart,接着我们进入初始化的项目下。安装echarts,npminstallecharts-S//或...

无所不能,将 Vue 渲染到嵌入式液晶屏

该文章转载自公众号@前端时刻,https://mp.weixin.qq.com/s/WDHW36zhfNFVFVv4jO2vrA前言...

vue-element-admin 增删改查(五)(vue-element-admin怎么用)

此篇幅比较长,涉及到的小知识点也比较多,一定要耐心看完,记住学东西没有耐心可不行!!!一、添加和修改注:添加和编辑用到了同一个组件,也就是此篇文章你能学会如何封装组件及引用组件;第二能学会async和...

最全的 Vue 面试题+详解答案(vue面试题知识点大全)

前言本文整理了...

基于 vue3.0 桌面端朋友圈/登录验证+60s倒计时

今天给大家分享的是Vue3聊天实例中的朋友圈的实现及登录验证和倒计时操作。先上效果图这个是最新开发的vue3.x网页端聊天项目中的朋友圈模块。用到了ElementPlus...

不来看看这些 VUE 的生命周期钩子函数?| 原力计划

作者|huangfuyk责编|王晓曼出品|CSDN博客VUE的生命周期钩子函数:就是指在一个组件从创建到销毁的过程自动执行的函数,包含组件的变化。可以分为:创建、挂载、更新、销毁四个模块...

Vue3.5正式上线,父传子props用法更丝滑简洁

前言Vue3.5在2024-09-03正式上线,目前在Vue官网显最新版本已经是Vue3.5,其中主要包含了几个小改动,我留意到日常最常用的改动就是props了,肯定是用Vue3的人必用的,所以针对性...

Vue 3 生命周期完整指南(vue生命周期及使用)

Vue2和Vue3中的生命周期钩子的工作方式非常相似,我们仍然可以访问相同的钩子,也希望将它们能用于相同的场景。...

救命!这 10 个 Vue3 技巧藏太深了!性能翻倍 + 摸鱼神器全揭秘

前端打工人集合!是不是经常遇到这些崩溃瞬间:Vue3项目越写越卡,组件通信像走迷宫,复杂逻辑写得脑壳疼?别慌!作为在一线摸爬滚打多年的老前端,今天直接甩出10个超实用的Vue3实战技巧,手把...

怎么在 vue 中使用 form 清除校验状态?

在Vue中使用表单验证时,经常需要清除表单的校验状态。下面我将介绍一些方法来清除表单的校验状态。1.使用this.$refs...

取消回复欢迎 发表评论: