解決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;
}
可以看到它直接返回了類中的全局變量defaultExecutorType,我們?cè)僭陬惖念^部尋找一下這個(gè)變量:
protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
找到了,Spring為我們提供的默認(rèn)執(zhí)行器類型為Simple,它的類型一共有三種:
/**
* @author Clinton Begin
*/
public enum ExecutorType {
SIMPLE, REUSE, BATCH
}
仔細(xì)觀察一下,發(fā)現(xiàn)有3個(gè)枚舉類型,其中有一個(gè)BATCH是否和批量操作有關(guān)呢?我們看一下mybatis官方文檔中對(duì)這三個(gè)值的描述:
- ExecutorType.SIMPLE: 這個(gè)執(zhí)行器類型不做特殊的事情。它為每個(gè)語(yǔ)句的執(zhí)行創(chuàng)建一個(gè)新的預(yù)處理語(yǔ)句。
- ExecutorType.REUSE: 這個(gè)執(zhí)行器類型會(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ù)類型,分別是
- Connection connection - ExecutorType execType - TransactionIsolationLevel level - boolean autoCommit
官方文檔中對(duì)這些參數(shù)也有詳細(xì)的解釋:
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 枚舉包裝器, 稱為 TransactionIsolationLevel, 否則它們按預(yù)期的方式來(lái)工作,并有 JDBC 支持的 5 級(jí)
NONE, READ_UNCOMMITTED READ_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é)
簡(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的寫法為
<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ú)頭緒,然后就自己重新寫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è)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
Spring中的EurekaServer啟動(dòng)詳解
這篇文章主要介紹了Spring中的EurekaServer啟動(dòng)詳解,初始化eureka,包含eureka集群的同步和發(fā)布注冊(cè),這個(gè)方法時(shí)重寫ServletContextListener#contextInitialized,是eureka啟動(dòng)的入口了,需要的朋友可以參考下2023-11-11
SpringBoot集成Aviator實(shí)現(xiàn)參數(shù)校驗(yàn)的示例代碼
在實(shí)際開(kāi)發(fā)中,參數(shù)校驗(yàn)是保障系統(tǒng)穩(wěn)定和數(shù)據(jù)可靠性的重要措施,Aviator 是一個(gè)高性能的表達(dá)式引擎,它能夠簡(jiǎn)化復(fù)雜的邏輯判斷并提升參數(shù)校驗(yàn)的靈活性,本文將介紹如何在 Spring Boot 中集成 Aviator,并利用它來(lái)實(shí)現(xiàn)靈活的參數(shù)校驗(yàn),需要的朋友可以參考下2025-02-02
java switch語(yǔ)句使用注意的四大細(xì)節(jié)
很多朋友在使用java switch語(yǔ)句時(shí),可能沒(méi)有注意到一些細(xì)節(jié),本文將詳細(xì)介紹使用java switch語(yǔ)句四大要點(diǎn),需要的朋友可以參考下2012-12-12
Java 中POI 導(dǎo)入EXCEL2003 和EXCEL2007的實(shí)現(xiàn)方法
這篇文章主要介紹了Java 中POI 導(dǎo)入EXCEL2003 和EXCEL2007的實(shí)現(xiàn)方法的相關(guān)資料,希望通過(guò)本文大家能掌握理解這種方法,需要的朋友可以參考下2017-09-09
淺談java中Math.random()與java.util.random()的區(qū)別
下面小編就為大家?guī)?lái)一篇淺談java中Math.random()與java.util.random()的區(qū)別。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-09-09
Springboot 整合通用mapper和pagehelper展示分頁(yè)數(shù)據(jù)的問(wèn)題(附github源碼)
這篇文章主要介紹了Springboot 整合通用mapper和pagehelper展示分頁(yè)數(shù)據(jù)(附github源碼),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09
Intellij Mybatis連接Mysql數(shù)據(jù)庫(kù)
最近在搞android的項(xiàng)目,在開(kāi)發(fā)過(guò)程中遇到了好多問(wèn)題,今天小編給大家說(shuō)下mybatis連接MySQL數(shù)據(jù)庫(kù)的方法,感興趣的朋友跟著小編一起學(xué)習(xí)吧2016-10-10

