后端与系统架构图文讲义1141 字

MyBatis批量插入几千条数据,请慎用foreach

·全库 581 / 611

《MyBatis批量插入几千条数据,请慎用foreach》共 5 页、0.1 万字,通篇围绕 缓存、MySQL 展开,归在「后端与系统架构」这一层。

覆盖缓存MySQL

适合给 AI 系统搭底座、要管得住的人

目录骨架(1 节)
  1. foreach 遇到数量大,性能瓶颈

原 PDF 已逐页还原成图,共 5 页,这里先放前 3 页,其中 1 页识别出了标题。右侧文字由 OCR 按版面重排,可能有个别错字,以图为准;点图可全屏放大。

本讲义目录 · 3 页
  1. 01近日,项目中有一个耗时较长的 Job…
  2. 02它强调,当插入数量很多时,不能一次性…
  3. 03foreach 遇到数量大,性能瓶颈
011 / 3
第 1 页
第 1 页

近日,项目中有一个耗时较长的 Job…

近日,项目中有一个耗时较长的 Job 存在 CPU 占用过高的的问题,经排查发现,主要时 间消耗在往 MyBatis 中批量插入数据。mapper configuration 是用 foreach 循环做的, 差不多是这样。(由于项目保密,以下代码均为自己手写的 demo 代码)

1 <insert id="batchInsert" parameterType="java.util.List"> insert into tablel (field1,field2)values

<foreach collection="list" item="t" index="index" separator=","> (#{ t.field1 },#{ t.field2 })

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

转化为:

虽然这个 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.

022 / 3
第 2 页
第 2 页

它强调,当插入数量很多时,不能一次性…

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: 2 some database such as Oracle here does not support. 3 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)wi11 4 be hit, and eventually possibly DB stack error if the statement itself become too

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

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

从资料中可知,默认执行器类型为 Simple,会为每个语句创建一个新的预处理语句, 也就是创建一个 PreparedStatement 对象。在我们的项目中,会不停地使用批量插入这 个方法,而因为 MyBatis 对于含有<foreach>的语句,无法采用缓存,那么在每次调用 方法时,都会重新解析 sql 语句。

1 Internally,it still generates the same single insert statement with many placeholders as the JDBC code above. 2 MyBatis has an ability to cache PreparedStatement, but this statement cannot be cached because it contains<foreach /> 3 element and the statement varies depending on the parameters. As a result, MyBatis has to 1)evaluate the foreach part and 2) 4 parse the statement string to build parameter mapping [ 1 ] on every execution of this statement. 5 And these steps are relatively costly process when the statement string is big and contains many placeholders. 6 [ 1 ] simply put, it is a mapping between placeholders and the parameters.

033 / 3
第 3 页:foreach 遇到数量大,性能瓶颈
第 3 页

foreach 遇到数量大,性能瓶颈

根据上述资料可以看出,耗时主要花费在循环操作上。由于我使用 foreach 循环后有 5000+个 values,因此这个 PreparedStatement 特别长,包含了很多占位符,而占位符 和参数的映射耗费了大量时间。此外,根据相关资料的研究表明,values 的增加与所需 解析时间呈指数型增长,因此这个循环操作需要更多的时间来完成。

项目实践发现,当表的列数较多(超过 20),以及一次性插入的行数较多(上万条)时,插入性能非 常差,通常需要 20 分钟以上 这个时候就需要观察曲线了,10-100 个来讲是很快的,当然也要根据项目请来 看,总之建议 100 个就 ok 了,不要太高。

Batchlnsert 模式 也是官方针对批量数据插入优化的方法之一 http://www.mybatis.org/mybatis-dynamic-sq/docs/insert.html

SqLSession session = SqlSessionFactory.openSession (ExecutorType. BATCH); try { TableMapper mapper = session.getMapper (TabLeMapper.class); //自定义你的方法来获取需要插入的数据 List<TableRecord> records = getRecordsToInsert (); //BatchInsert BatchInsert<TableRecord> batchInsert = insert (records) .into (table) .map (id).toProperty ("id") •map (field1).toProperty ("field1") .map (field2).toProperty ("field2")

.render (RenderingStrategy.MYBATIS3); batchInsert.insertStatements ().stream ().forEach (mapper::insert); session.commit (); 16 } finally { session.close ();

资料里没有你的场景?

把你手上的数据和想解决的那个环节发上来,我们按具体情况回,不复述方法论。

发布需求