首页 > 其他分享 >MyBatis批量插入不用foreach

MyBatis批量插入不用foreach

时间:2024-06-20 09:11:40浏览次数:16  
标签:批量 插入 foreach statement MyBatis data1 data2

原文链接:MyBatis批量插入不用foreach – 每天进步一点点 (longkui.site)

近日,项目中有一个耗时较长的Job存在CPU占用过高的问题,经排查发现,主要时间消耗在往MyBatis中批量插入数据。

mapper configuration是用foreach循环做的,差不多是这样。(由于项目保密,以下代码均为自己手写的demo代码)

< INSERT id = "batchInsert" parameterType = "java.util.List" > INSERT INTO USER ( id, NAME ) VALUES < foreach collection = "list" item = "model" INDEX = "index" SEPARATOR = "," > (#{model.id}, #{model.name}) </foreach> </insert>

这个方法提升批量插入速度的原理是,将传统的:

INSERT INTO `table1` (`field1`, `field2`) VALUES ("data1", "data2"); INSERT INTO `table1` (`field1`, `field2`) VALUES ("data1", "data2"); INSERT INTO `table1` (`field1`, `field2`) VALUES ("data1", "data2"); INSERT INTO `table1` (`field1`, `field2`) VALUES ("data1", "data2"); INSERT INTO `table1` (`field1`, `field2`) VALUES ("data1", "data2");

转化为:

INSERT INTO `table1` (`field1`, `field2`) VALUES ("data1", "data2"), ("data1", "data2"), ("data1", "data2"), ("data1", "data2"), ("data1", "data2");

在MySql Docs中也提到过这个trick,如果要优化插入速度时,可以将许多小型操作组合到一个大型操作中。

理想情况下,这样可以在单个连接中一次性发送许多新行的数据,并将所有索引更新和一致性检查延迟到最后才进行。

乍看上去这个foreach没有问题,但是经过项目实践发现,当表的列数较多(20+),以及一次性插入的行数较多(5000+)时,整个插入的耗时十分漫长,达到了14分钟,这是不能忍的。

在资料中也提到了一句话:

Of course don’t combine ALL of them, if the amount is HUGE. Say you have 1000 rows you need to insert, then don’t do it one at a time. You shouldn’t equally try to have all 1000 rows in a single query. Instead break it into smaller sizes.

它强调,当插入数量很多时,不能一次性全放在一条语句里。可是为什么不能放在同一条语句里呢?这条语句为什么会耗时这么久呢?

资料发现:

Insert inside Mybatis foreach is not batch, this is a single (could become giant) SQL statement and that brings drawbacks:

  • some database such as Oracle here does not support.
  • in relevant cases: there will be a large number of records to insert and the database configured limit (by default around 2000 parameters per statement) will be hit, and eventually possibly DB stack error if the statement itself become too large.

Iteration over the collection must not be done in the mybatis XML. Just execute a simple Insertstatement in a Java Foreach loop. The most important thing is the session Executor type.

SqlSession session = sessionFactory.openSession(ExecutorType.BATCH);for (Model model : list) { session.insert("insertStatement", model);}session.flushStatements();

Unlike default ExecutorType.SIMPLE, the statement will be prepared once and executed for each record to insert.

从资料中可知,默认执行器类型为Simple,会为每个语句创建一个新的预处理语句,也就是创建一个PreparedStatement对象。

在我们的项目中,会不停地使用批量插入这个方法,而因为MyBatis对于含有<foreach>的语句,无法采用缓存,那么在每次调用方法时,都会重新解析sql语句。

Internally, it still generates the same single insert statement with many placeholders as the JDBC code above.

MyBatis has an ability to cache PreparedStatement, but this statement cannot be cached because it contains <foreach /> element and the statement varies depending on the parameters. As a result, MyBatis has to 1) evaluate the foreach part and 2) parse the statement string to build parameter mapping [1] on every execution of this statement.

And these steps are relatively costly process when the statement string is big and contains many placeholders.

从上述资料可知,耗时就耗在,由于我foreach后有5000+个values,所以这个PreparedStatement特别长,包含了很多占位符,对于占位符和参数的映射尤其耗时。并且,查阅相关资料可知,values的增长与所需的解析时间,是呈指数型增长的。

所以,如果非要使用 foreach 的方式来进行批量插入的话,可以考虑减少一条 insert 语句中 values 的个数,最好能达到上面曲线的最底部的值,使速度最快。一般按经验来说,一次性插20~50行数量是比较合适的,时间消耗也能接受。

重点来了。上面讲的是,如果非要用<foreach>的方式来插入,可以提升性能的方式。而实际上,MyBatis文档中写批量插入的时候,是推荐使用另外一种方法。

SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH); try { SimpleTableMapper mapper = session.getMapper(SimpleTableMapper.class); List<SimpleTableRecord> records = getRecordsToInsert(); // not shown   BatchInsert<SimpleTableRecord> batchInsert = insert(records) .into(simpleTable) .map(id).toProperty("id") .map(firstName).toProperty("firstName") .map(lastName).toProperty("lastName") .map(birthDate).toProperty("birthDate") .map(employed).toProperty("employed") .map(occupation).toProperty("occupation") .build() .render(RenderingStrategy.MYBATIS3);   batchInsert.insertStatements().stream().forEach(mapper::insert);   session.commit(); } finally { session.close(); }

即基本思想是将 MyBatis session 的 executor type 设为 Batch ,然后多次执行插入语句。就类似于JDBC的下面语句一样。

Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=UTF-8&useServerPrepStmts=false&rewriteBatchedStatements=true","root","root"); connection.setAutoCommit(false); PreparedStatement ps = connection.prepareStatement( "insert into tb_user (name) values(?)"); for (int i = 0; i < stuNum; i++) { ps.setString(1,name); ps.addBatch(); } ps.executeBatch(); connection.commit(); connection.close();

经过试验,使用了 ExecutorType.BATCH 的插入方式,性能显著提升,不到 2s 便能全部插入完成。

总结一下,如果MyBatis需要进行批量插入,推荐使用 ExecutorType.BATCH 的插入方式,如果非要使用 <foreach>的插入的话,需要将每次插入的记录控制在 20~50 左右。

标签:批量,插入,foreach,statement,MyBatis,data1,data2
From: https://www.cnblogs.com/longkui-site/p/18257999

相关文章

  • Automa实现的Gmail个人邮箱批量发邮件-带定时功能-实战原创
    文章目录前言一、Gmail个人邮箱批量发邮件是什么?二、操作演示1.工作流全貌2.数据读取3.创建空文件4.写入数据5.切换标签页6.定时功能总结高效办公新技能:使用Automa和Gmail实现定时邮件发送,提升效率!前言Gmail个人邮箱批量发邮件-自定义内容,这个插件之前做的是安......
  • postman导入不同参数,批量执行接口
    日常工作中经常因为某些不可抗力而导致需要批量重新调用接口,看看怎么利用postman来解决此类问题1.定义接口模板 2.保存到一个collection中3.runcollection4.选择参数文件,参数格式用逗号分割   5.运行批量执行脚本注意文本格式的数字要加上双引号,避免导入后开头......
  • MyBatis
    MyBatis1、MyBatis是什么框架?MyBatis是一个持久层框架,它是Java编程语言中用于操作关系型数据库的一个工具。MyBatis的主要作用是简化数据库访问的过程,提供了一种方便、灵活的方式来进行SQL操作。相比传统的JDBC编程方式,MyBatis可以更加高效地管理数据库连接、执行SQL......
  • mybatis-mp 高级用法:ORM+SQL模板,真正意义实现ORM!!!
    官网:mybatis-mp.cn目前ORM以JPAPLUS为首的ORM,遇到稍微复杂的、或者数据库特性函数时通常需要自己写sql,或代码中,或xml中,这就有点难受了1:有没有好的办法?mybatis-mp的做法就是ORM+SQL模板,SQL模板不仅仅是sql字符串,它还帮你替换关系的信息:列SysUserRo......
  • Mybatis的Mapper中方法入参什么时候加@Param
    参数情况:一个基本类型--不需要多个基本类型--需要一个对象 --不需要多个对象  --不需要一个集合  --不需要 单个基本类型不用加@ParamMapper接口方法:voiddeleteUserById(LonguserId);XML中的SQL语句:<deleteid="deleteUserById"parameterType=......
  • 批量生产千万级数据 推送到kafka代码
    1、批量规则生成代码1、随机IP生成代码2、指定时间范围内随机日期生成代码3、随机中文名生成代码。packagecom.wfg.flink.connector.utils;importjava.time.LocalDate;importjava.time.LocalDateTime;importjava.time.LocalTime;importjava.util.ArrayList;i......
  • MybatisPlus之继承IService
    有一些简简单单的数据库增删改查还需要Service到Mapper一步步地来吗?答案是否定地,甚至代码都不用实现哦。这就是因为IService接口提供了一些基础功能的实现IService和ServiceImplIService只是一个接口,它并不能实现功能,如果你的service的接口继承它,继承过来的只是接口没有功......
  • springboot 使用 doris-streamloader 到doris 防止批量更新 事务卡主
    背景:使用mybatis批量实时和更新doris时经常出现连接不上的错误,导致kafka死信队列堆积很多滞后消费https://doris.apache.org/zh-CN/docs/2.0/ecosystem/doris-streamloader/packagecom.jiaoda.sentiment.data.etl.service.update;importcn.hutool.core.text.CharSequenc......
  • MyBatis之ResultMap
    ResultMap的属性列表 resultMap标签介绍constructor-用于在实例化类时,注入结果到构造方法中idArg-ID参数;标记出作为ID的结果可以帮助提高整体性能arg-将被注入到构造方法的一个普通结果id–一个ID结果;标记出作为ID的结果可以帮助提高整体性能,用于主键......
  • MyBatis Plus Generator代码生成
    一、MyBatisPlusGeneratorMyBatisPlus是一个功能强大的持久层框架,它简化了MyBatis的使用,提供了许多便捷的功能。其中,MyBatisPlusGenerator是一个强大的代码生成器,可以帮助我们快速地根据数据库表结构生成对应的实体类、映射文件和DAO接口。在MyBatisPlusGenerator中......