MyBatis批量插入幾千條數據,請慎用foreach

近日,項目中有一個耗時較長的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
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,363評論 6 532
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,497評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,305評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,962評論 1 311
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,727評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,193評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,257評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,411評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,945評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,777評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,978評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,519評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,216評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,642評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,878評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,657評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,960評論 2 373

推薦閱讀更多精彩內容