MyBatis批量插入幾千條數(shù)據(jù)响牛,請(qǐng)慎用foreach

近日妓湘,項(xiàng)目中有一個(gè)耗時(shí)較長(zhǎng)的Job存在CPU占用過(guò)高的問(wèn)題查蓉,經(jīng)排查發(fā)現(xiàn),主要時(shí)間消耗在往MyBatis中批量插入數(shù)據(jù)榜贴。mapper configuration是用foreach循環(huán)做的豌研,差不多是這樣。(由于項(xiàng)目保密,以下代碼均為自己手寫的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>

這個(gè)方法提升批量插入速度的原理是鹃共,將傳統(tǒng)的:

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");

轉(zhuǎn)化為:

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

在MySql Docs中也提到過(guò)這個(gè)trick鬼佣,如果要優(yōu)化插入速度時(shí),可以將許多小型操作組合到一個(gè)大型操作中霜浴。理想情況下晶衷,這樣可以在單個(gè)連接中一次性發(fā)送許多新行的數(shù)據(jù),并將所有索引更新和一致性檢查延遲到最后才進(jìn)行阴孟。

乍看上去這個(gè)foreach沒(méi)有問(wèn)題晌纫,但是經(jīng)過(guò)項(xiàng)目實(shí)踐發(fā)現(xiàn),當(dāng)表的列數(shù)較多(20+)温眉,以及一次性插入的行數(shù)較多(5000+)時(shí)缸匪,整個(gè)插入的耗時(shí)十分漫長(zhǎng),達(dá)到了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.

它強(qiáng)調(diào),當(dāng)插入數(shù)量很多時(shí)闯冷,不能一次性全放在一條語(yǔ)句里砂心。可是為什么不能放在同一條語(yǔ)句里呢蛇耀?這條語(yǔ)句為什么會(huì)耗時(shí)這么久呢辩诞?我查閱了資料發(fā)現(xiàn):

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.

從資料中可知,默認(rèn)執(zhí)行器類型為Simple纺涤,會(huì)為每個(gè)語(yǔ)句創(chuàng)建一個(gè)新的預(yù)處理語(yǔ)句译暂,也就是創(chuàng)建一個(gè)PreparedStatement對(duì)象。在我們的項(xiàng)目中撩炊,會(huì)不停地使用批量插入這個(gè)方法外永,而因?yàn)镸yBatis對(duì)于含有<foreach>的語(yǔ)句,無(wú)法采用緩存拧咳,那么在每次調(diào)用方法時(shí)伯顶,都會(huì)重新解析sql語(yǔ)句。

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.

從上述資料可知骆膝,耗時(shí)就耗在祭衩,由于我foreach后有5000+個(gè)values,所以這個(gè)PreparedStatement特別長(zhǎng)阅签,包含了很多占位符掐暮,對(duì)于占位符和參數(shù)的映射尤其耗時(shí)。并且政钟,查閱相關(guān)資料可知劫乱,values的增長(zhǎng)與所需的解析時(shí)間织中,是呈指數(shù)型增長(zhǎng)的。

圖片

所以衷戈,如果非要使用 foreach 的方式來(lái)進(jìn)行批量插入的話狭吼,可以考慮減少一條 insert 語(yǔ)句中 values 的個(gè)數(shù),最好能達(dá)到上面曲線的最底部的值殖妇,使速度最快刁笙。一般按經(jīng)驗(yàn)來(lái)說(shuō),一次性插20~50行數(shù)量是比較合適的谦趣,時(shí)間消耗也能接受疲吸。

重點(diǎn)來(lái)了。上面講的是前鹅,如果非要用<foreach>的方式來(lái)插入摘悴,可以提升性能的方式。而實(shí)際上舰绘,MyBatis文檔中寫批量插入的時(shí)候蹂喻,是推薦使用另外一種方法。(可以看 http://www.mybatis.org/mybatis-dynamic-sql/docs/insert.html 中 Batch Insert Support 標(biāo)題里的內(nèi)容)

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 設(shè)為 Batch 捂寿,然后多次執(zhí)行插入語(yǔ)句口四。就類似于JDBC的下面語(yǔ)句一樣。

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();

經(jīng)過(guò)試驗(yàn)秦陋,使用了 ExecutorType.BATCH 的插入方式蔓彩,性能顯著提升,不到 2s 便能全部插入完成驳概。

總結(jié)一下赤嚼,如果MyBatis需要進(jìn)行批量插入,推薦使用 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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末待榔,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子流济,更是在濱河造成了極大的恐慌锐锣,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,188評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件绳瘟,死亡現(xiàn)場(chǎng)離奇詭異雕憔,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)糖声,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門斤彼,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)分瘦,“玉大人,你說(shuō)我怎么就攤上這事琉苇〕懊担” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,562評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵并扇,是天一觀的道長(zhǎng)去团。 經(jīng)常有香客問(wèn)我,道長(zhǎng)穷蛹,這世上最難降的妖魔是什么土陪? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,893評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮肴熏,結(jié)果婚禮上鬼雀,老公的妹妹穿的比我還像新娘。我一直安慰自己蛙吏,他們只是感情好源哩,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,917評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著出刷,像睡著了一般璧疗。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上馁龟,一...
    開(kāi)封第一講書(shū)人閱讀 51,708評(píng)論 1 305
  • 那天崩侠,我揣著相機(jī)與錄音,去河邊找鬼坷檩。 笑死却音,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的矢炼。 我是一名探鬼主播系瓢,決...
    沈念sama閱讀 40,430評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼句灌!你這毒婦竟也來(lái)了夷陋?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,342評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤胰锌,失蹤者是張志新(化名)和其女友劉穎骗绕,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體资昧,經(jīng)...
    沈念sama閱讀 45,801評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡酬土,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,976評(píng)論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了格带。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片撤缴。...
    茶點(diǎn)故事閱讀 40,115評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡刹枉,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出屈呕,到底是詐尸還是另有隱情微宝,我是刑警寧澤,帶...
    沈念sama閱讀 35,804評(píng)論 5 346
  • 正文 年R本政府宣布凉袱,位于F島的核電站芥吟,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏专甩。R本人自食惡果不足惜钟鸵,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,458評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望涤躲。 院中可真熱鬧棺耍,春花似錦、人聲如沸种樱。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,008評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)浸赫。三九已至绘沉,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間岂昭,已是汗流浹背以现。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,135評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留约啊,地道東北人邑遏。 一個(gè)月前我還...
    沈念sama閱讀 48,365評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像恰矩,于是被迫代替她去往敵國(guó)和親记盒。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,055評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容