Spring JdbcTemplate 批量插入操作
阿新 • • 發佈:2018-11-09
做專案中碰到一個批量資料插入,給自己提個醒做個記錄。
框架是:spring+mybatis+oracle
1.一開始我是拿SqlSessionTemplate 去操作insert mybatis用的迴圈list的方式。結果發現只能插入6000條,超過6000的時候會報記憶體溢位,具體原因也沒搞清楚。(後期有機會再去看看)結果肯定是不滿意的,就想到了第2種方案。
2.SqlSessionTemplate 的 batchInsert 方式結果是可以的,但是1萬條資料耗時122s,時間太長了,這個客戶肯定接受不了。那沒有辦法只能再想其他方案了。
3.最終方案:JdbcTemplate 的 batchUpdate 方式試了一下速度果然嗖嗖的。1萬條資料耗時10s。
接下來上程式碼:
public static final int BATCH_SIZE = 5000; public void batchInsertJdbc(String sql, List<Object[]> batchArgs) { try { int fromIndex = 0; int toIndex = BATCH_SIZE; sql = "INSERT INTO cx_out_call_back_task "; sql+=" (ID,CUST_NAME,TELEPHONE,PLATENUM,PLATECOLORTYPE,ETCCARD,CARTYPE,IDNUMBER,CARDTIME,"; sql+="CARDPOINT,ENDFREECONSUME,ACCOUNTBALANCE,CARDBALANCE,ORDERSOURCE,NAME_TYPE,"; sql+="CARDCHANNEL,CALL_TIME,TENANT_ID,source,STATE,REMARK) "; sql+=" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; while (fromIndex != batchArgs.size()) { if (toIndex > batchArgs.size()) { toIndex = batchArgs.size(); } this.jdbcTemplate.batchUpdate(sql, batchArgs.subList(fromIndex, toIndex)); fromIndex = toIndex; toIndex += BATCH_SIZE; if (toIndex > batchArgs.size()) toIndex = batchArgs.size(); } } catch (Exception e) { throw new DaoException("批量插入失敗", e); } }