解決Mybatis 大數(shù)據(jù)量的批量insert問(wèn)題
通過(guò)Mybatis做7000+數(shù)據(jù)量的批量插入的時(shí)候報(bào)錯(cuò)了,error log如下:
, (’G61010352’, ’610103199208291214’, ’學(xué)生52’, ’G61010350’,’610103199109920192’,’學(xué)生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
可以看到這種異常無(wú)法捕捉,僅能看到異常指向了druid和ibatis的原碼處,初步猜測(cè)是由于默認(rèn)的SqlSession無(wú)法支持這個(gè)數(shù)量級(jí)的批量操作,下面就結(jié)合源碼和官方文檔具體看一看。
源碼分析項(xiàng)目使用的是Spring+Mybatis,在Dao層是通過(guò)Spring提供的SqlSessionTemplate來(lái)獲取SqlSession的:
@Resource(name = 'sqlSessionTemplate')private SqlSessionTemplate sqlSessionTemplate;public SqlSessionTemplate getSqlSessionTemplate() { return sqlSessionTemplate;}
為了驗(yàn)證,接下看一下它是如何提供SqlSesion的,打開(kāi)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()); }
接下來(lái)再點(diǎn)開(kāi)getDefaultExecutorType這個(gè)方法:
public ExecutorType getDefaultExecutorType() { return defaultExecutorType; }
可以看到它直接返回了類(lèi)中的全局變量defaultExecutorType,我們?cè)僭陬?lèi)的頭部尋找一下這個(gè)變量:
protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
找到了,Spring為我們提供的默認(rèn)執(zhí)行器類(lèi)型為Simple,它的類(lèi)型一共有三種:
/** * @author Clinton Begin */public enum ExecutorType { SIMPLE, REUSE, BATCH}
仔細(xì)觀察一下,發(fā)現(xiàn)有3個(gè)枚舉類(lèi)型,其中有一個(gè)BATCH是否和批量操作有關(guān)呢?我們看一下mybatis官方文檔中對(duì)這三個(gè)值的描述:
- ExecutorType.SIMPLE: 這個(gè)執(zhí)行器類(lèi)型不做特殊的事情。它為每個(gè)語(yǔ)句的執(zhí)行創(chuàng)建一個(gè)新的預(yù)處理語(yǔ)句。
- ExecutorType.REUSE: 這個(gè)執(zhí)行器類(lèi)型會(huì)復(fù)用預(yù)處理語(yǔ)句。
- ExecutorType.BATCH:這個(gè)執(zhí)行器會(huì)批量執(zhí)行所有更新語(yǔ)句,如果 SELECT 在它們中間執(zhí)行還會(huì)標(biāo)定它們是 必須的,來(lái)保證一個(gè)簡(jiǎn)單并易于理解的行為。
可以看到我的使用的SIMPLE會(huì)為每個(gè)語(yǔ)句創(chuàng)建一個(gè)新的預(yù)處理語(yǔ)句,也就是創(chuàng)建一個(gè)PreparedStatement對(duì)象,即便我們使用druid連接池進(jìn)行處理,依然是每次都會(huì)向池中put一次并加入druid的cache中。這個(gè)效率可想而知,所以那個(gè)異常也有可能是insert timeout導(dǎo)致等待時(shí)間超過(guò)數(shù)據(jù)庫(kù)驅(qū)動(dòng)的最大等待值。
好了,已解決問(wèn)題為主,根據(jù)分析我們選擇通過(guò)BATCH的方式來(lái)創(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ù)類(lèi)型,分別是
- Connection connection- ExecutorType execType- TransactionIsolationLevel level- boolean autoCommit
官方文檔中對(duì)這些參數(shù)也有詳細(xì)的解釋?zhuān)?/b>
SqlSessionFactory 有六個(gè)方法可以用來(lái)創(chuàng)建 SqlSession 實(shí)例。通常來(lái)說(shuō),如何決定是你 選擇下面這些方法時(shí):
Transaction (事務(wù)): 你想為 session 使用事務(wù)或者使用自動(dòng)提交(通常意味著很多 數(shù)據(jù)庫(kù)和/或 JDBC 驅(qū)動(dòng)沒(méi)有事務(wù))?
Connection (連接): 你想 MyBatis 獲得來(lái)自配置的數(shù)據(jù)源的連接還是提供你自己
Execution (執(zhí)行): 你想 MyBatis 復(fù)用預(yù)處理語(yǔ)句和/或批量更新語(yǔ)句(包括插入和 刪除)?
所以根據(jù)需求選擇即可,由于我們要做的事情是批量insert,所以我們選擇SqlSession openSession(ExecutorType execType, boolean autoCommit)
順帶一提關(guān)于TransactionIsolationLevel也就是我們經(jīng)常提起的事務(wù)隔離級(jí)別,官方文檔中也介紹的很到位:
MyBatis 為事務(wù)隔離級(jí)別調(diào)用使用一個(gè) Java 枚舉包裝器, 稱(chēng)為 TransactionIsolationLevel, 否則它們按預(yù)期的方式來(lái)工作,并有 JDBC 支持的 5 級(jí)
NONE,READ_UNCOMMITTEDREAD_COMMITTED,REPEATABLE_READ,SERIALIZA BLE)解決問(wèn)題
回歸正題,初步找到了問(wèn)題原因,那我們換一中SqlSession的獲取方式再試試看。
testing… 2minutes later…
不幸的是,依舊報(bào)相同的錯(cuò)誤,看來(lái)不僅僅是ExecutorType的問(wèn)題,那會(huì)不會(huì)是一次commit的數(shù)據(jù)量過(guò)大導(dǎo)致響應(yīng)時(shí)間過(guò)長(zhǎng)呢?上面我也提到了這種可能性,那么就再分批次處理試試,也就是說(shuō),在同一事務(wù)范圍內(nèi),分批commit insert batch。具體看一下Dao層的代碼實(shí)現(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的個(gè)數(shù) int batchLastIndex = batchCount;// 每批最后一個(gè)的下標(biāo) 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è)置下一批下標(biāo) batchLastIndex = index + (batchCount - 1); } } batchSqlSession.commit(); } finally { batchSqlSession.close(); } return Tools.getBoolean(result); }
再次測(cè)試,程序沒(méi)有報(bào)異常,總共7728條數(shù)據(jù) insert的時(shí)間大約為10s左右,如下圖所示,
簡(jiǎn)單記錄一下Mybatis批量insert大數(shù)據(jù)量數(shù)據(jù)的解決方案,僅供參考,Tne End。
補(bǔ)充:mybatis批量插入報(bào)錯(cuò):’,’附近有錯(cuò)誤
mybatis批量插入的時(shí)候報(bào)錯(cuò),報(bào)錯(cuò)信息‘,’附近有錯(cuò)誤
mapper.xml的寫(xiě)法為
<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語(yǔ)句
INSERT INTO USER_LOG (USER_ID, OP_TYPE, CONTENT, IP, OP_ID, OP_TIME) VALUES ( (?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?) )
調(diào)試的時(shí)候還是把sql復(fù)制到navicate中進(jìn)行檢查,就報(bào)了上面的錯(cuò)。這個(gè)錯(cuò)看起來(lái)毫無(wú)頭緒,然后就自己重新寫(xiě)insert語(yǔ)句,發(fā)現(xiàn)正確的語(yǔ)句應(yīng)該為
INSERT INTO USER_LOG (USER_ID, OP_TYPE, CONTENT, IP, OP_ID, OP_TIME) VALUES (?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?)
比之前的sql少了外面的括號(hào),此時(shí)運(yùn)行成功,所以mapper.xml中應(yīng)該把opern=”(” close=”)”刪除即可。
多說(shuō)一句,批量插入的時(shí)候也可以把要插入的數(shù)據(jù)組裝成List<實(shí)體>,這樣就不用傳這么多的參數(shù)了。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. MySQL圖形化管理工具的使用及說(shuō)明2. MySQL數(shù)據(jù)庫(kù)復(fù)合查詢(xún)操作實(shí)戰(zhàn)3. MySQL+Navicat安裝配置保姆級(jí)教程4. 用shell抽取,更新db2的數(shù)據(jù)5. MySQL的雙寫(xiě)緩沖區(qū)Doublewrite Buffer詳解6. 深入理解r2dbc在mysql中的使用7. DB2 9產(chǎn)品說(shuō)明書(shū)在線參考地址(http)8. sqlserver數(shù)據(jù)庫(kù)導(dǎo)入方法的詳細(xì)圖文教程9. short int、long、float、double使用問(wèn)題說(shuō)明10. MySQL三大日志(binlog、redo log和undo log)圖文詳解
