欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

MyBatis批量插入幾千條數(shù)據(jù)為何慎用foreach

 更新時(shí)間:2022年10月31日 14:44:56   作者:huanghanqian  
這篇文章主要介紹了MyBatis批量插入幾千條數(shù)據(jù)為何慎用foreach問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

MyBatis批量插入幾千條數(shù)據(jù)慎用foreach

近日,項(xiàng)目中有一個(gè)耗時(shí)較長的Job存在CPU占用過高的問題,經(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中也提到過這個(gè)trick,如果要優(yōu)化插入速度時(shí),可以將許多小型操作組合到一個(gè)大型操作中。理想情況下,這樣可以在單個(gè)連接中一次性發(fā)送許多新行的數(shù)據(jù),并將所有索引更新和一致性檢查延遲到最后才進(jìn)行。

乍看上去這個(gè)foreach沒有問題,但是經(jīng)過項(xiàng)目實(shí)踐發(fā)現(xiàn),當(dāng)表的列數(shù)較多(20+),以及一次性插入的行數(shù)較多(5000+)時(shí),整個(gè)插入的耗時(shí)十分漫長,達(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í),不能一次性全放在一條語句里??墒菫槭裁床荒芊旁谕粭l語句里呢?這條語句為什么會(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è)語句創(chuàng)建一個(gè)新的預(yù)處理語句,也就是創(chuàng)建一個(gè)PreparedStatement對象。

在我們的項(xiàng)目中,會(huì)不停地使用批量插入這個(gè)方法,而因?yàn)镸yBatis對于含有<foreach>的語句,無法采用緩存,那么在每次調(diào)用方法時(shí),都會(huì)重新解析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.

從上述資料可知,耗時(shí)就耗在,由于我foreach后有5000+個(gè)values,所以這個(gè)PreparedStatement特別長,包含了很多占位符,對于占位符和參數(shù)的映射尤其耗時(shí)。并且,查閱相關(guān)資料可知,values的增長與所需的解析時(shí)間,是呈指數(shù)型增長的。

               

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

重點(diǎn)來了。

上面講的是,如果非要用<foreach>的方式來插入,可以提升性能的方式。而實(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í)行插入語句。就類似于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();

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

總結(jié)一下

如果MyBatis需要進(jìn)行批量插入,推薦使用 ExecutorType.BATCH 的插入方式,如果非要使用 <foreach> 的插入的話,需要將每次插入的記錄控制在 20~50 左右。

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

參考資料:

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. http://www.dbjr.com.cn/article/203743.htm

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

相關(guān)文章

  • 詳解eclipse項(xiàng)目中.classpath文件的使用

    詳解eclipse項(xiàng)目中.classpath文件的使用

    這篇文章主要介紹了詳解eclipse項(xiàng)目中.classpath文件的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • 利用Java實(shí)現(xiàn)簡單的詞法分析器實(shí)例代碼

    利用Java實(shí)現(xiàn)簡單的詞法分析器實(shí)例代碼

    眾所周知編譯原理中的詞法分析算是很重要的一個(gè)部分,原理比較簡單,不過網(wǎng)上大部分都是用C語言或者C++來編寫,因?yàn)樽罱趯W(xué)習(xí)Java,故用Java語言實(shí)現(xiàn)了簡單的詞法分析器。感興趣的朋友們可以參考借鑒,下面來一起看看吧。
    2016-12-12
  • Docker和?Containerd?的區(qū)別解析

    Docker和?Containerd?的區(qū)別解析

    containerd?是一個(gè)來自?Docker?的高級容器運(yùn)行時(shí),并實(shí)現(xiàn)了?CRI?規(guī)范,它是從?Docker?項(xiàng)目中分離出來,之后?containerd?被捐贈(zèng)給云原生計(jì)算基金會(huì)(CNCF)為容器社區(qū)提供創(chuàng)建新容器解決方案的基礎(chǔ),這篇文章主要介紹了Docker和?Containerd?的區(qū)別,需要的朋友可以參考下
    2024-03-03
  • Java實(shí)現(xiàn)簡單的學(xué)生教師管理系統(tǒng)

    Java實(shí)現(xiàn)簡單的學(xué)生教師管理系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)簡單的學(xué)生教師管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • SpringBoot手動(dòng)使用EhCache的方法示例

    SpringBoot手動(dòng)使用EhCache的方法示例

    本篇文章主要介紹了SpringBoot手動(dòng)使用EhCache的方法示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-02-02
  • java如何讀取文件目錄返回樹形結(jié)構(gòu)

    java如何讀取文件目錄返回樹形結(jié)構(gòu)

    這篇文章主要介紹了java如何讀取文件目錄返回樹形結(jié)構(gòu)問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • java基礎(chǔ)之方法詳解

    java基礎(chǔ)之方法詳解

    這篇文章主要介紹了java基礎(chǔ)之方法詳解,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java基礎(chǔ)的小伙伴們有非常好的幫助,需要的朋友可以參考下
    2021-04-04
  • 一文讀懂IDEA里面的Artifact到底是什么

    一文讀懂IDEA里面的Artifact到底是什么

    這篇文章主要介紹了IDEA里面的Artifact到底是什么,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2021-01-01
  • Mybatis圖文并茂講解分頁插件

    Mybatis圖文并茂講解分頁插件

    使用過mybatis的人都知道,mybatis本身就很小且簡單,sql寫在xml里,統(tǒng)一管理和優(yōu)化。缺點(diǎn)當(dāng)然也有,比如我們使用過程中,要使用到分頁,如果用最原始的方式的話,1.查詢分頁數(shù)據(jù),2.獲取分頁長度,也就是說要使用到兩個(gè)方法才能完成分頁
    2022-07-07
  • java實(shí)現(xiàn)構(gòu)造無限層級樹形菜單

    java實(shí)現(xiàn)構(gòu)造無限層級樹形菜單

    這篇文章主要介紹了java實(shí)現(xiàn)構(gòu)造無限層級樹形菜單,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-09-09

最新評論