解決Mybatis 大數(shù)據(jù)量的批量insert問題
前言
通過Mybatis做7000+數(shù)據(jù)量的批量插入的時候報錯了,error log如下:
, ('G61010352', '610103199208291214', '學生52', 'G61010350', '610103199109920192', '學生50', '07', '01', '0104', ' ', , ' ', ' ', current_timestamp, current_timestamp )
被中止,呼叫 getNextException 以取得原因。
at org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler.handleError(AbstractJdbc2Statement.java:2743) at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:411) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2892) at com.alibaba.druid.filter.FilterChainImpl.statement_executeBatch(FilterChainImpl.java:2596) at com.alibaba.druid.wall.WallFilter.statement_executeBatch(WallFilter.java:473) at com.alibaba.druid.filter.FilterChainImpl.statement_executeBatch(FilterChainImpl.java:2594) at com.alibaba.druid.filter.FilterAdapter.statement_executeBatch(FilterAdapter.java:2474) at com.alibaba.druid.filter.FilterEventAdapter.statement_executeBatch(FilterEventAdapter.java:279) at com.alibaba.druid.filter.FilterChainImpl.statement_executeBatch(FilterChainImpl.java:2594) at com.alibaba.druid.proxy.jdbc.StatementProxyImpl.executeBatch(StatementProxyImpl.java:192) at com.alibaba.druid.pool.DruidPooledPreparedStatement.executeBatch(DruidPooledPreparedStatement.java:559) at org.apache.ibatis.executor.BatchExecutor.doFlushStatements(BatchExecutor.java:108) at org.apache.ibatis.executor.BaseExecutor.flushStatements(BaseExecutor.java:127) at org.apache.ibatis.executor.BaseExecutor.flushStatements(BaseExecutor.java:120) at org.apache.ibatis.executor.BaseExecutor.commit(BaseExecutor.java:235) at org.apache.ibatis.executor.CachingExecutor.commit(CachingExecutor.java:112) at org.apache.ibatis.session.defaults.DefaultSqlSession.commit(DefaultSqlSession.java:196) at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:390) ... 39 more
可以看到這種異常無法捕捉,僅能看到異常指向了druid和ibatis的原碼處,初步猜測是由于默認的SqlSession無法支持這個數(shù)量級的批量操作,下面就結(jié)合源碼和官方文檔具體看一看。
源碼分析
項目使用的是Spring+Mybatis,在Dao層是通過Spring提供的SqlSessionTemplate來獲取SqlSession的:
@Resource(name = "sqlSessionTemplate") private SqlSessionTemplate sqlSessionTemplate; public SqlSessionTemplate getSqlSessionTemplate() { return sqlSessionTemplate; }
為了驗證,接下看一下它是如何提供SqlSesion的,打開SqlSessionTemplate的源碼,看一下它的構(gòu)造方法:
/** * Constructs a Spring managed SqlSession with the {@code SqlSessionFactory} * provided as an argument. * * @param sqlSessionFactory */ public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType()); }
接下來再點開getDefaultExecutorType這個方法:
public ExecutorType getDefaultExecutorType() { return defaultExecutorType; }
可以看到它直接返回了類中的全局變量defaultExecutorType,我們再在類的頭部尋找一下這個變量:
protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
找到了,Spring為我們提供的默認執(zhí)行器類型為Simple,它的類型一共有三種:
/** * @author Clinton Begin */ public enum ExecutorType { SIMPLE, REUSE, BATCH }
仔細觀察一下,發(fā)現(xiàn)有3個枚舉類型,其中有一個BATCH是否和批量操作有關(guān)呢?我們看一下mybatis官方文檔中對這三個值的描述:
- ExecutorType.SIMPLE
: 這個執(zhí)行器類型不做特殊的事情。它為每個語句的執(zhí)行創(chuàng)建一個新的預(yù)處理語句。
- ExecutorType.REUSE
: 這個執(zhí)行器類型會復用預(yù)處理語句。
- ExecutorType.BATCH
:這個執(zhí)行器會批量執(zhí)行所有更新語句,如果 SELECT 在它們中間執(zhí)行還會標定它們是 必須的,來保證一個簡單并易于理解的行為。
可以看到我的使用的SIMPLE會為每個語句創(chuàng)建一個新的預(yù)處理語句,也就是創(chuàng)建一個PreparedStatement對象,即便我們使用druid連接池進行處理,依然是每次都會向池中put一次并加入druid的cache中。這個效率可想而知,所以那個異常也有可能是insert timeout導致等待時間超過數(shù)據(jù)庫驅(qū)動的最大等待值。
好了,已解決問題為主,根據(jù)分析我們選擇通過BATCH的方式來創(chuàng)建SqlSession,官方也提供了一系列重載方法:
SqlSession openSession() SqlSession openSession(boolean autoCommit) SqlSession openSession(Connection connection) SqlSession openSession(TransactionIsolationLevel level) SqlSession openSession(ExecutorType execType,TransactionIsolationLevel level) SqlSession openSession(ExecutorType execType) SqlSession openSession(ExecutorType execType, boolean autoCommit) SqlSession openSession(ExecutorType execType, Connection connection)
可以觀察到主要有四種參數(shù)類型,分別是
- Connection connection - ExecutorType execType - TransactionIsolationLevel level - boolean autoCommit
官方文檔中對這些參數(shù)也有詳細的解釋:
SqlSessionFactory 有六個方法可以用來創(chuàng)建 SqlSession 實例。通常來說,如何決定是你 選擇下面這些方法時:
Transaction (事務(wù))
: 你想為 session 使用事務(wù)或者使用自動提交(通常意味著很多 數(shù)據(jù)庫和/或 JDBC 驅(qū)動沒有事務(wù))?
Connection (連接)
: 你想 MyBatis 獲得來自配置的數(shù)據(jù)源的連接還是提供你自己
Execution (執(zhí)行)
: 你想 MyBatis 復用預(yù)處理語句和/或批量更新語句(包括插入和 刪除)?
所以根據(jù)需求選擇即可,由于我們要做的事情是批量insert,所以我們選擇SqlSession openSession(ExecutorType execType, boolean autoCommit)
順帶一提關(guān)于TransactionIsolationLevel也就是我們經(jīng)常提起的事務(wù)隔離級別,官方文檔中也介紹的很到位:
MyBatis 為事務(wù)隔離級別調(diào)用使用一個 Java 枚舉包裝器, 稱為 TransactionIsolationLevel, 否則它們按預(yù)期的方式來工作,并有 JDBC 支持的 5 級
NONE, READ_UNCOMMITTED READ_COMMITTED, REPEATABLE_READ, SERIALIZA BLE)
解決問題
回歸正題,初步找到了問題原因,那我們換一中SqlSession的獲取方式再試試看。
testing… 2minutes later…
不幸的是,依舊報相同的錯誤,看來不僅僅是ExecutorType的問題,那會不會是一次commit的數(shù)據(jù)量過大導致響應(yīng)時間過長呢?上面我也提到了這種可能性,那么就再分批次處理試試,也就是說,在同一事務(wù)范圍內(nèi),分批commit insert batch。具體看一下Dao層的代碼實現(xiàn):
@Override public boolean insertCrossEvaluation(List<CrossEvaluation> members) throws Exception { // TODO Auto-generated method stub int result = 1; SqlSession batchSqlSession = null; try { batchSqlSession = this.getSqlSessionTemplate() .getSqlSessionFactory() .openSession(ExecutorType.BATCH, false);// 獲取批量方式的sqlsession int batchCount = 1000;// 每批commit的個數(shù) int batchLastIndex = batchCount;// 每批最后一個的下標 for (int index = 0; index < members.size();) { if (batchLastIndex >= members.size()) { batchLastIndex = members.size(); result = result * batchSqlSession.insert("MutualEvaluationMapper.insertCrossEvaluation",members.subList(index, batchLastIndex)); batchSqlSession.commit(); System.out.println("index:" + index+ " batchLastIndex:" + batchLastIndex); break;// 數(shù)據(jù)插入完畢,退出循環(huán) } else { result = result * batchSqlSession.insert("MutualEvaluationMapper.insertCrossEvaluation",members.subList(index, batchLastIndex)); batchSqlSession.commit(); System.out.println("index:" + index+ " batchLastIndex:" + batchLastIndex); index = batchLastIndex;// 設(shè)置下一批下標 batchLastIndex = index + (batchCount - 1); } } batchSqlSession.commit(); } finally { batchSqlSession.close(); } return Tools.getBoolean(result); }
再次測試,程序沒有報異常,總共7728條數(shù)據(jù) insert的時間大約為10s左右,如下圖所示,
總結(jié)
簡單記錄一下Mybatis批量insert大數(shù)據(jù)量數(shù)據(jù)的解決方案,僅供參考,Tne End。
補充:mybatis批量插入報錯:','附近有錯誤
mybatis批量插入的時候報錯,報錯信息‘,'附近有錯誤
mapper.xml的寫法為
<insert id="insertByBatch"> INSERT INTO USER_LOG (USER_ID, OP_TYPE, CONTENT, IP, OP_ID, OP_TIME) VALUES <foreach collection="userIds" item="userId" open="(" close=")" separator=","> (#{rateId}, #{opType}, #{content}, #{ipStr}, #{userId}, #{opTime}, </foreach> </insert>
打印的sql語句
INSERT INTO USER_LOG (USER_ID, OP_TYPE, CONTENT, IP, OP_ID, OP_TIME) VALUES ( (?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?) )
調(diào)試的時候還是把sql復制到navicate中進行檢查,就報了上面的錯。這個錯看起來毫無頭緒,然后就自己重新寫insert語句,發(fā)現(xiàn)正確的語句應(yīng)該為
INSERT INTO USER_LOG (USER_ID, OP_TYPE, CONTENT, IP, OP_ID, OP_TIME) VALUES (?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?)
比之前的sql少了外面的括號,此時運行成功,所以mapper.xml中應(yīng)該把opern=”(” close=”)”刪除即可。
多說一句,批量插入的時候也可以把要插入的數(shù)據(jù)組裝成List<實體>,這樣就不用傳這么多的參數(shù)了。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
詳細談?wù)凧ava中l(wèi)ong和double的原子性
原子性是指一個操作或多個操作要么全部執(zhí)行,且執(zhí)行的過程不會被任何因素打斷,要么就都不執(zhí)行,下面這篇文章主要給大家介紹了關(guān)于Java中l(wèi)ong和double原子性的相關(guān)資料,需要的朋友可以參考下2021-08-08如何使用Spring Boot實現(xiàn)自定義Spring Boot插件
在本文中,我們介紹了如何使用 Spring Boot 實現(xiàn)自定義插件,使用自定義插件可以幫助我們快速地添加一些額外的功能,提高系統(tǒng)的可擴展性和可維護性,感興趣的朋友跟隨小編一起看看吧2023-06-06詳解Spring Boot Admin監(jiān)控服務(wù)上下線郵件通知
本篇文章主要介紹了詳解Spring Boot Admin監(jiān)控服務(wù)上下線郵件通知,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12Java數(shù)據(jù)結(jié)構(gòu)之隊列的簡單定義與使用方法
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)之隊列的簡單定義與使用方法,簡單描述了隊列的功能、特點,并結(jié)合java實例形式分析了隊列的簡單定義與使用方法,需要的朋友可以參考下2017-10-10