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

MyBatis批量插入數(shù)據(jù)你還在用foreach?你們的服務(wù)器沒崩?

開發(fā) 后端
近日,項(xiàng)目中有一個耗時較長的Job存在CPU占用過高的問題,經(jīng)排查發(fā)現(xiàn),主要時間消耗在往MyBatis中批量插入數(shù)據(jù)。

 [[435918]]

近日,項(xiàng)目中有一個耗時較長的Job存在CPU占用過高的問題,經(jīng)排查發(fā)現(xiàn),主要時間消耗在往MyBatis中批量插入數(shù)據(jù)。mapper configuration是用foreach循環(huán)做的,差不多是這樣。(由于項(xiàng)目保密,以下代碼均為自己手寫的demo代碼) 

  1. <insert id="batchInsert" parameterType="java.util.List">  
  2.     insert into USER (id, name) values  
  3.     <foreach collection="list" item="model" index="index" separator=",">   
  4.         (#{model.id}, #{model.name})  
  5.     </foreach>  
  6. </insert> 

這個方法提升批量插入速度的原理是,將傳統(tǒng)的: 

  1. INSERT INTO `table1` (`field1`, `field2`) VALUES ("data1", "data2");  
  2. INSERT INTO `table1` (`field1`, `field2`) VALUES ("data1", "data2");  
  3. INSERT INTO `table1` (`field1`, `field2`) VALUES ("data1", "data2");  
  4. INSERT INTO `table1` (`field1`, `field2`) VALUES ("data1", "data2");  
  5. INSERT INTO `table1` (`field1`, `field2`) VALUES ("data1", "data2"); 

轉(zhuǎn)化為: 

  1. INSERT INTO `table1` (`field1`, `field2`)   
  2. VALUES ("data1", "data2"),  
  3. ("data1", "data2"),  
  4. ("data1", "data2"),  
  5. ("data1", "data2"),  
  6. ("data1", "data2");  

在MySql Docs中也提到過這個trick,如果要優(yōu)化插入速度時,可以將許多小型操作組合到一個大型操作中。理想情況下,這樣可以在單個連接中一次性發(fā)送許多新行的數(shù)據(jù),并將所有索引更新和一致性檢查延遲到最后才進(jìn)行。

乍看上去這個foreach沒有問題,但是經(jīng)過項(xiàng)目實(shí)踐發(fā)現(xiàn),當(dāng)表的列數(shù)較多(20+),以及一次性插入的行數(shù)較多(5000+)時,整個插入的耗時十分漫長,達(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ù)量很多時,不能一次性全放在一條語句里。可是為什么不能放在同一條語句里呢?這條語句為什么會耗時這么久呢?我查閱了資料發(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. 

  1. SqlSession session = sessionFactory.openSession(ExecutorType.BATCH);  
  2. for (Model model : list) {  
  3.     session.insert("insertStatement", model);  
  4.  
  5. session.flushStatements(); 

Unlike default ExecutorType.SIMPLE, the statement will be prepared once and executed for each record to insert.

從資料中可知,默認(rèn)執(zhí)行器類型為Simple,會為每個語句創(chuàng)建一個新的預(yù)處理語句,也就是創(chuàng)建一個PreparedStatement對象。在我們的項(xiàng)目中,會不停地使用批量插入這個方法,而因?yàn)镸yBatis對于含有<foreach>的語句,無法采用緩存,那么在每次調(diào)用方法時,都會重新解析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特別長,包含了很多占位符,對于占位符和參數(shù)的映射尤其耗時。并且,查閱相關(guān)資料可知,values的增長與所需的解析時間,是呈指數(shù)型增長的。

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

重點(diǎn)來了。上面講的是,如果非要用<foreach>的方式來插入,可以提升性能的方式。而實(shí)際上,MyBatis文檔中寫批量插入的時候,是推薦使用另外一種方法。(可以看 http://www.mybatis.org/mybatis-dynamic-sql/docs/insert.html 中 Batch Insert Support 標(biāo)題里的內(nèi)容) 

  1. SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH);  
  2. try {  
  3.     SimpleTableMapper mapper = session.getMapper(SimpleTableMapper.class);  
  4.     List<SimpleTableRecord> records = getRecordsToInsert(); // not shown  
  5.     BatchInsert<SimpleTableRecord> batchInsert = insert(records)  
  6.             .into(simpleTable)  
  7.             .map(id).toProperty("id")  
  8.             .map(firstName).toProperty("firstName")  
  9.             .map(lastName).toProperty("lastName")  
  10.             .map(birthDate).toProperty("birthDate")  
  11.             .map(employed).toProperty("employed")  
  12.             .map(occupation).toProperty("occupation")  
  13.             .build()  
  14.             .render(RenderingStrategy.MYBATIS3);  
  15.     batchInsert.insertStatements().stream().forEach(mapper::insert);  
  16.     session.commit();  
  17. } finally {  
  18.     session.close();  

即基本思想是將 MyBatis session 的 executor type 設(shè)為 Batch ,然后多次執(zhí)行插入語句。就類似于JDBC的下面語句一樣。 

  1. Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=UTF-8&useServerPrepStmts=false&rewriteBatchedStatements=true","root","root"); 
  2. connection.setAutoCommit(false);  
  3. PreparedStatement ps = connection.prepareStatement(  
  4.         "insert into tb_user (name) values(?)");  
  5. for (int i = 0; i < stuNum; i++) {  
  6.     ps.setString(1,name);  
  7.     ps.addBatch();  
  8.  
  9. ps.executeBatch();  
  10. connection.commit();  
  11. connection.close(); 

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

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

 

責(zé)任編輯:龐桂玉 來源: java版web項(xiàng)目
相關(guān)推薦

2020-02-21 14:15:40

SimpleDateFJava多線程

2022-09-23 09:44:17

MyBatisforeach

2024-03-26 10:30:37

Mybatis擴(kuò)展庫API

2012-07-19 10:03:32

2015-07-09 11:32:26

AWSIaaS云計(jì)算

2024-07-10 10:08:36

項(xiàng)目多表關(guān)聯(lián)哈希

2024-11-12 16:28:34

2023-08-30 09:16:38

PandasPython

2017-02-27 13:22:29

戴爾

2021-09-27 07:56:41

MyBatis Plu數(shù)據(jù)庫批量插入

2022-09-29 10:06:56

SQLMySQL服務(wù)端

2020-03-04 14:05:35

戴爾

2021-10-09 06:59:36

技術(shù)MyBatis數(shù)據(jù)

2025-04-02 08:47:23

DOM文檔結(jié)構(gòu)API

2023-12-04 09:14:00

數(shù)據(jù)庫MySQL

2023-01-05 07:55:59

Zookeeper服務(wù)注冊

2019-09-21 21:32:34

數(shù)據(jù)庫SQL分布式

2017-02-13 12:20:13

大數(shù)據(jù)備份技術(shù)

2011-03-18 13:41:50

2018-03-15 08:25:53

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號

主站蜘蛛池模板: 日韩欧美1区2区 | 亚洲不卡在线观看 | 国产综合视频 | 亚洲欧美激情精品一区二区 | 韩国久久精品 | 国产在线小视频 | 红桃成人在线 | 国产精品免费一区二区三区四区 | 国产中文原创 | 国产永久免费 | 精品日韩在线观看 | 精品免费视频 | 国产综合一区二区 | 美女在线视频一区二区三区 | 国产精品伦一区二区三级视频 | 国产成人一区在线 | 亚洲精品电影在线观看 | 国产精品欧美一区喷水 | a级大毛片| 99pao成人国产永久免费视频 | 中文字幕在线不卡 | 成年人在线观看 | 密室大逃脱第六季大神版在线观看 | 成人一区在线观看 | 成人黄色在线观看 | 国家一级黄色片 | 亚洲国产成人av好男人在线观看 | 午夜ww| 操久久 | 日一区二区 | 蜜桃免费一区二区三区 | 国产精品中文字幕在线播放 | 亚洲 欧美 另类 综合 偷拍 | 欧美精品国产精品 | 亚洲精品视频观看 | 国产精品久久久久久吹潮 | 亚洲高清视频在线观看 | 毛片a | 精久久久| 亚洲成人福利 | 男人午夜视频 |