當前位置: 妍妍網 > 碼農

求求你們了,MyBatis 批次插入別再亂用 foreach 了,5000 條數據花了 14 分鐘。。

2024-06-27碼農

大家好,我是磊哥。

近日,計畫中有一個耗時較長的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,如果要最佳化插入速度時,可以將許多小型操作組合到一個大型操作中。理想情況下,這樣可以在單個連線中一次性發送許多新行的數據,並將所有索引更新和一致性檢查延遲到最後才進行。

插播一條:如果你近期準備面試跳槽,建議在ddkk.com線上刷題,涵蓋 一萬+ 道 Java 面試題,幾乎覆蓋了所有主流技術面試題,還有市面上最全的技術五百套,精品系列教程,免費提供。

乍看上去這個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 Insert statement 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對於含有 的語句,無法采用緩存,那麽在每次呼叫方法時,都會重新解析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行數量是比較合適的,時間消耗也能接受。

    重點來了。上面講的是,如果非要用 的方式來插入,可以提升效能的方式。而實際上,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的下面語句一樣。

    插播一條:如果你近期準備面試跳槽,建議在ddkk.com線上刷題,涵蓋 一萬+ 道 Java 面試題,幾乎覆蓋了所有主流技術面試題,還有市面上最全的技術五百套,精品系列教程,免費提供。

    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 的插入方式,如果非要使用 的插入的話,需要將每次插入的記錄控制在 20~50 左右。

    🔥 磊哥私藏精品 熱門推薦 🔥