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

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

·全库 591 / 611

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

覆盖MySQL延迟缓存

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

目录骨架(2 节)
  1. MyBatis 批量插入几干条数据,请慎用
  2. foreach

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

本讲义目录 · 3 页
  1. 01MyBatis 批量插入几干条数据,请慎用
  2. 02Unlike default Exe…
  3. 031= the single row …
011 / 3
第 1 页:MyBatis 批量插入几干条数据,请慎用
第 1 页

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

foreach

来自一个真实项目中的问题,有一个耗时较长的 lob 存在 CPU 占用过高的问题,经排查发现,主要时间消 耗在往 MyBatis 中批量插入数据。mapper configuration 是用 foreach 循环做的,差不多是这样。

<insert id="batchInsert" parameterType="java.util.List"> insert into USER (id, name)values <foreach collection="1ist" item="model" index="index" separator=" (#{ model.id },#{ model.name }) </foreach> </insert>

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

转化为:

"data2"), "'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.

022 / 3
第 2 页
第 2 页

Unlike default Exe…

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 =

session.insert ("insertStatement"

session.flushstatementsO;

Unlike default ExecutorType.SIMPLE, the statement will be prepared once and executed for each record to insert. 从资料中可知,默认执行器类型为 Simple,会为每个语句创建一个新的预处理语句,也就是创建一个 PreparedStatement 对象。在我们的项目中,会不停地使用批量插入这个方法,而因为 MyBatis 对于含有 的语句,无法采用缓存,那么在每次调用方法时,都会重新解析 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 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 的增长 与所需的解析时间,是呈指数型增长的。

sessionFactory.opensession (ExecutorType.BATCH);

033 / 3
第 3 页
第 3 页

1= the single row …

in seconds

1= the single row insert, >1 multiple rows insert 所以,如果非要使用 foreach 的方式来进行批量插入的话,可以考虑減少一条 insert 语句中 values 的个 数,最好能达到上面曲线的最底部的值,使速度最快。一般按经验来说,一次性插 20~50 行数量是比较合 适的,时间消耗也能接受。 重点来了。上面讲的是,如果非要用<foreach>的方式来插入,可以提升性能的方式。而实际上, MyBatis 文档中写批量插入的时候,是推荐使用另外一种方法。(可以看 http://www.mybatis.org/myb atis-dynamic-sq ldocs/insert.html 中 Batch Insert Support 标题里的内容)

SqlSession session = sqlSessionFactory.opensession (ExecutorType. BATCH); try SimpleTablemapper mapper List<SimpleTableRecord> records = getRecordsToInsert ();// not shown

BatchInsert<SimpleTableRecord> batchInsert = insert (records) .into (simpleTable)

.map (id).toproperty ("id") .map (firstName).toProperty ("firstName") .map (lastName).toProperty ("1astName") .map (birthDate).toProperty ("birthDate") .map (employed).toProperty ("employed") .map (occupation).toProperty ("occupation")

.render (Renderingstrategy . MYBATIS3);

batchInsert.insertStatements ().stream (.forEach (mapper::insert);

session.commit (); } finally {

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

1000

Number of rows in a single insert

= session.getMapper (SimpleTableapper.class);

资料里没有你的场景?

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

发布需求