解決Mybatis 大數據量的批量insert問題
通過Mybatis做7000+數據量的批量插入的時候報錯了,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無法支持這個數量級的批量操作,下面就結合源碼和官方文檔具體看一看。
源碼分析項目使用的是Spring+Mybatis,在Dao層是通過Spring提供的SqlSessionTemplate來獲取SqlSession的:
@Resource(name = 'sqlSessionTemplate')private SqlSessionTemplate sqlSessionTemplate;public SqlSessionTemplate getSqlSessionTemplate() { return sqlSessionTemplate;}
為了驗證,接下看一下它是如何提供SqlSesion的,打開SqlSessionTemplate的源碼,看一下它的構造方法:
/** * 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為我們提供的默認執行器類型為Simple,它的類型一共有三種:
/** * @author Clinton Begin */public enum ExecutorType { SIMPLE, REUSE, BATCH}
仔細觀察一下,發現有3個枚舉類型,其中有一個BATCH是否和批量操作有關呢?我們看一下mybatis官方文檔中對這三個值的描述:
- ExecutorType.SIMPLE: 這個執行器類型不做特殊的事情。它為每個語句的執行創建一個新的預處理語句。
- ExecutorType.REUSE: 這個執行器類型會復用預處理語句。
- ExecutorType.BATCH:這個執行器會批量執行所有更新語句,如果 SELECT 在它們中間執行還會標定它們是 必須的,來保證一個簡單并易于理解的行為。
可以看到我的使用的SIMPLE會為每個語句創建一個新的預處理語句,也就是創建一個PreparedStatement對象,即便我們使用druid連接池進行處理,依然是每次都會向池中put一次并加入druid的cache中。這個效率可想而知,所以那個異常也有可能是insert timeout導致等待時間超過數據庫驅動的最大等待值。
好了,已解決問題為主,根據分析我們選擇通過BATCH的方式來創建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)
可以觀察到主要有四種參數類型,分別是
- Connection connection- ExecutorType execType- TransactionIsolationLevel level- boolean autoCommit
官方文檔中對這些參數也有詳細的解釋:
SqlSessionFactory 有六個方法可以用來創建 SqlSession 實例。通常來說,如何決定是你 選擇下面這些方法時:
Transaction (事務): 你想為 session 使用事務或者使用自動提交(通常意味著很多 數據庫和/或 JDBC 驅動沒有事務)?
Connection (連接): 你想 MyBatis 獲得來自配置的數據源的連接還是提供你自己
Execution (執行): 你想 MyBatis 復用預處理語句和/或批量更新語句(包括插入和 刪除)?
所以根據需求選擇即可,由于我們要做的事情是批量insert,所以我們選擇SqlSession openSession(ExecutorType execType, boolean autoCommit)
順帶一提關于TransactionIsolationLevel也就是我們經常提起的事務隔離級別,官方文檔中也介紹的很到位:
MyBatis 為事務隔離級別調用使用一個 Java 枚舉包裝器, 稱為 TransactionIsolationLevel, 否則它們按預期的方式來工作,并有 JDBC 支持的 5 級
NONE,READ_UNCOMMITTEDREAD_COMMITTED,REPEATABLE_READ,SERIALIZA BLE)解決問題
回歸正題,初步找到了問題原因,那我們換一中SqlSession的獲取方式再試試看。
testing… 2minutes later…
不幸的是,依舊報相同的錯誤,看來不僅僅是ExecutorType的問題,那會不會是一次commit的數據量過大導致響應時間過長呢?上面我也提到了這種可能性,那么就再分批次處理試試,也就是說,在同一事務范圍內,分批commit insert batch。具體看一下Dao層的代碼實現:
@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的個數 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;// 數據插入完畢,退出循環 } else { result = result * batchSqlSession.insert('MutualEvaluationMapper.insertCrossEvaluation',members.subList(index, batchLastIndex)); batchSqlSession.commit(); System.out.println('index:' + index+ ' batchLastIndex:' + batchLastIndex); index = batchLastIndex;// 設置下一批下標 batchLastIndex = index + (batchCount - 1); } } batchSqlSession.commit(); } finally { batchSqlSession.close(); } return Tools.getBoolean(result); }
再次測試,程序沒有報異常,總共7728條數據 insert的時間大約為10s左右,如下圖所示,
簡單記錄一下Mybatis批量insert大數據量數據的解決方案,僅供參考,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 ( (?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?) )
調試的時候還是把sql復制到navicate中進行檢查,就報了上面的錯。這個錯看起來毫無頭緒,然后就自己重新寫insert語句,發現正確的語句應該為
INSERT INTO USER_LOG (USER_ID, OP_TYPE, CONTENT, IP, OP_ID, OP_TIME) VALUES (?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?)
比之前的sql少了外面的括號,此時運行成功,所以mapper.xml中應該把opern=”(” close=”)”刪除即可。
多說一句,批量插入的時候也可以把要插入的數據組裝成List<實體>,這樣就不用傳這么多的參數了。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章:
