首页 > 其他分享 >MyBatis 别再乱用 foreach 批量插入了,5000 数据用了 14 分钟,实力劝退。。

MyBatis 别再乱用 foreach 批量插入了,5000 数据用了 14 分钟,实力劝退。。

时间:2022-08-31 16:22:27浏览次数:96  
标签:insert 5000 14 插入 foreach statement data1 data2

近日,项目中有一个耗时较长的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.

[1] simply put, it is a mapping between placeholders and the parameters.

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

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

重点来了。上面讲的是,如果非要用<foreach>的方式来插入,可以提升性能的方式。而实际上,MyBatis文档中写批量插入的时候,是推荐使用另外一种方法。(可以看 http://www.mybatis.org/mybatis-dynamic-sql/docs/insert.html 中 Batch Insert Support 标题里的内容)

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 左右。

参考资料

  1. https://dev.mysql.com/doc/refman/5.6/en/insert-optimization.html
  2. https://stackoverflow.com/questions/19682414/how-can-mysql-insert-millions-records-fast
  3. https://stackoverflow.com/questions/32649759/using-foreach-to-do-batch-insert-with-mybatis/40608353
  4. https://blog.csdn.net/wlwlwlwl015/article/details/50246717
  5. http://blog.harawata.net/2016/04/bulk-insert-multi-row-vs-batch-using.html
  6. https://www.red-gate.com/simple-talk/sql/performance/comparing-multiple-rows-insert-vs-single-row-insert-with-three-data-load-methods/
  7. https://stackoverflow.com/questions/7004390/java-batch-insert-into-mysql-very-slow
  8. http://www.mybatis.org/mybatis-dynamic-sql/docs/insert.html

原文链接:https://blog.csdn.net/huanghanqian/article/details/83177178

版权声明:本文为CSDN博主「huanghanqian」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

近期热文推荐:

1.1,000+ 道 Java面试题及答案整理(2022最新版)

2.劲爆!Java 协程要来了。。。

3.Spring Boot 2.x 教程,太全了!

4.别再写满屏的爆爆爆炸类了,试试装饰器模式,这才是优雅的方式!!

5.《Java开发手册(嵩山版)》最新发布,速速下载!

觉得不错,别忘了随手点赞+转发哦!

标签:insert,5000,14,插入,foreach,statement,data1,data2
From: https://www.cnblogs.com/javastack/p/16643485.html

相关文章

  • P2312 [NOIP2014 提高组] 解方程
    求\(a_0+a_1x+a_2x^2+\cdots+a_nx^n=0\)在\([1,m]\)内的整数解(\(n\)和\(m\)均为正整数)。\(0<n\le100,|a_i|\le10^{10000},a_n≠0,m<10^6\)。首先是数学部分,......
  • P3514 [POI2011]LIZ-Lollipop
    给定长度为\(n\)的序列,里面的元素为1或2,求是否有一种方案,取出连续的一段,使得到的元素和等于给定的值,若可以则输出一种方案。多组询问,\(n,q\leq10^6\)。感觉有点水,典......
  • P1452/CF429D/P6247/P1429/P7883
    (P1452)给定\(n\)个点,求最远点对。\(n\leq5\times10^4\)。(CF429D)给定\(n\)个点,求最近点对。\(n\leq10^5\)。(P6247)给定\(n\)个点,求最近点对和最远点对。\(n\le......
  • 1470. 重新排列数组
    1470.重新排列数组给你一个数组nums,数组中有2n个元素,按[x1,x2,...,xn,y1,y2,...,yn]的格式排列。请你将数组按[x1,y1,x2,y2,...,xn,yn]格式重新排列,返回重排......
  • 大道如青天,协程来通信,Go lang1.18入门精炼教程,由白丁入鸿儒,Go lang通道channel的使
    众所周知,Golang的作用域相对严格,数据之间的通信往往要依靠参数的传递,但如果想在多个协程任务中间做数据通信,就需要通道(channel)的参与,我们可以把数据封装成一个对象,然后把......
  • Hyper Prefix Sets UVA - 11488
    题目链接思路我们对所有字符串建\(Trie\)树,求答案时,直接在插入新的字符串的时候,把答案更新一下就好了。代码#include<iostream>#include<cstdio>#include<cstri......
  • CCF 201409-1 相邻数对(C++)
    因为题目给的是不同的整数,所以就排序,然后for遍历找出差值为1的就好了#include<iostream>#include<bits/stdc++.h>#include<cstdio>usingnamespacestd;intn;i......
  • P1471 方差
    给定数列,维护区间平均数和区间方差,并支持区间修改。\(n\leq10^5,m\leq10^5\)。线段树维护平均数比较简单,重点在于如何维护方差。具体公式参考了这篇题解,就不详细展开,推......
  • P2375 [NOI2014] 动物园
    定义字符串的前\(i\)个字符组成的字符串中一最大子串\(T\)即使前缀也是后缀,且\(|T|\leqi/2\),则定义\(num[i]=|T|\),求\(num[i]+1\)之积\(mod\)1000000007。\(......
  • linux系统 BCM43142的网卡 安装
    检查网卡驱动:[paul@localhost~]$lspci|grepNetwork09:00.0Networkcontroller:BroadcomInc.andsubsidiariesBCM43142802.11b/g/n(rev01) 安装依赖:......