大家好,我是磊哥。
最近在項目中遇到了一個耗時較長的Job,其CPU占用率過高,經排查發現,主要時間消耗在通過mybatis進行批量數據插入。mapper配置文件中使用了foreach循環進行批量插入,大致如下所示。(由于項目保密,以下代碼均為自己手寫的demo代碼)
<insert id="batchInsert" parameterType="Java.util.List"> insert into USER (id, name) values <foreach Collection="list" index="index" item="model" 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文檔中也提到過這個技巧,如果要優化插入速度,可以將多個小操作合并成一個大操作。理想情況下,這樣可以在單個連接中一次性發送許多新行的數據,并將所有索引更新和一致性檢查推遲到最后進行。
乍一看,這個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();
與默認的ExecutorType.SIMPLE不同,BATCH類型的執行器會在每次插入記錄時準備一次語句并執行。
從資料中可以得知,默認的執行器類型為Simple,會為每個語句創建一個新的預處理語句,即創建一個PreparedStatement對象。在我們的項目中,會不斷地使用這個批量插入方法,而由于MyBatis無法對包含
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
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行的數量是比較合適的,時間消耗也能接受。
重點來了。上面講的是,如果非要使用
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 < 100000; i++) { ps.setString(1, "name_" + i); ps.addBatch(); } ps.executeBatch(); connection.commit();
經過試驗,使用ExecutorType.BATCH的插入方式,性能顯著提升,不到2秒便能全部插入完成。
總結一下,如果MyBatis需要進行批量插入,推薦使用ExecutorType.BATCH的插入方式,如果非要使用