成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

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

開發 后端
經排查發現,主要時間消耗在往 MyBatis 中批量插入數據。mapper configuration是用 foreach 循環做的,差不多是這樣。(由于項目保密,以下代碼均為自己手寫的demo代碼)。

近日,項目中有一個耗時較長的 Job 存在 CPU 占用過高的問題。

<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:https://dev.mysql.com/doc/refman/5.6/en/insert-optimization.html中也提到過這個 trick,如果要優化插入速度時,可以將許多小型操作組合到一個大型操作中。理想情況下,這樣可以在單個連接中一次性發送許多新行的數據,并將所有索引更新和一致性檢查延遲到最后才進行。

乍看上去這個 foreach 沒有問題,但是經過項目實踐發現,當表的列數較多(20+),以及一次性插入的行數較多(5000+)時,整個插入的耗時十分漫長,達到了 14 分鐘,這是不能忍的。在[資料]https://stackoverflow.com/questions/19682414/how-can-mysql-insert-millions-records-fast中也提到了一句話:

?

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.

?

它強調,當插入數量很多時,不能一次性全放在一條語句里。可是為什么不能放在同一條語句里呢?這條語句為什么會耗時這么久呢?我查閱了[資料]https://stackoverflow.com/questions/32649759/using-foreach-to-do-batch-insert-with-mybatis/40608353發現:

?

「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.

?

從[資料]https://blog.csdn.net/wlwlwlwl015/article/details/50246717中可知,默認執行器類型為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.

?

從上述[資料] http://blog.harawata.net/2016/04/bulk-insert-multi-row-vs-batch-using.html 可知,耗時就耗在,由于我 foreach 后有 5000+ 個 values,所以這個PreparedStatement 特別長,包含了很多占位符,對于占位符和參數的映射尤其耗時。并且,查閱相關[資料]https://www.red-gate.com/simple-talk/sql/performance/comparing-multiple-rows-insert-vs-single-row-insert-with-three-data-load-methods 可知,values 的增長與所需的解析時間,是呈指數型增長的。

所以,如果非要使用 foreach 的方式來進行批量插入的話,可以考慮減少一條 insert 語句中 values 的個數,最好能達到上面曲線的最底部的值,使速度最快。一般按[經驗]https://stackoverflow.com/questions/7004390/java-batch-insert-into-mysql-very-slow來說,一次性插 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 左右。

責任編輯:龐桂玉 來源: Java后端技術
相關推薦

2021-09-27 07:56:41

MyBatis Plu數據庫批量插入

2021-11-02 14:46:50

數據

2021-11-19 11:50:48

MyBatisforeachJava

2024-04-15 08:30:53

MySQLORM框架

2022-09-29 10:06:56

SQLMySQL服務端

2023-12-30 20:04:51

MyBatis框架數據

2021-10-09 06:59:36

技術MyBatis數據

2021-11-01 22:29:28

Python數據單身

2013-04-01 15:03:58

Android開發Android批量插入

2024-04-17 08:18:22

MyBatis批量插入SQL

2020-07-28 08:31:05

數據分析技術IT

2024-07-31 09:56:20

2024-03-07 08:08:51

SQL優化數據

2011-08-11 14:15:23

SQL Server索引碎片

2021-10-18 07:58:33

MyBatis Plu數據庫批量插入

2023-06-07 08:00:00

MySQL批量插入

2021-04-08 10:55:53

MySQL數據庫代碼

2020-07-19 21:26:48

網絡安全程序員技術

2011-08-04 18:00:47

SQLite數據庫批量數據

2018-06-21 09:12:01

編程語言Python數據分析
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 欧美在线 | 男人的天堂在线视频 | 在线看成人av | 亚洲综合日韩精品欧美综合区 | 久久国产精品精品 | 羞羞的视频在线 | 久久久国产亚洲精品 | 成人精品鲁一区一区二区 | 最近中文字幕第一页 | 四虎影音 | 天天av综合 | 毛片韩国 | 国产视频一区二区 | 欧美福利 | 亚洲综合五月天婷婷 | 国产精品久久久久久 | 亚洲国产欧美日韩 | 最新av在线网址 | 在线视频第一页 | 亚洲精品国产a久久久久久 午夜影院网站 | 欧美日韩不卡合集视频 | 岛国在线免费观看 | 国产成人精品一区二区三区在线 | 免费a v网站 | 亚洲精品成人av久久 | 一级黄色av电影 | 精品九九九 | 黑人巨大精品欧美一区二区免费 | 久久久久中文字幕 | 99久久久久国产精品免费 | 色视频网站 | 国产馆| 伦理二区| 99re在线视频 | 亚洲国产精品日韩av不卡在线 | 国产精品久久久久久久久免费高清 | 欧美在线视频一区 | 中文在线a在线 | 久久久久国产 | 中国一级毛片免费 | 玖玖综合网|