從 7 分鐘到 10 秒,Mybatis 批處理真的很強!
閱讀本文大概需要 7 分鐘。
來自:juejin.cn/post/7078237987011559460
ExecutorType.BATCH?這種的用法,另學(xué)藝不精,如果有錯的地方,還請大佬們指出更正。問題原因
簡單了解一下批處理背后的秘密,BatchExecutor
每次向數(shù)據(jù)庫發(fā)送的 SQL 語句的條數(shù)是有上限的,如果批量執(zhí)行的時候超過這個上限值,數(shù)據(jù)庫就會拋出異常,拒絕執(zhí)行這一批 SQL 語句,所以我們需要控制批量發(fā)送 SQL 語句的條數(shù)和頻率。
版本1-呱呱墜地
@Resource
private?某Mapper類?mapper實例對象;
private?int?BATCH?=?1000;
??private?void?doUpdateBatch(Date?accountDate,?List<某實體類>?data)?{
????SqlSession?batchSqlSession?=?null;
????try?{
??????if?(data?==?null?||?data.size()?==?0)?{
????????return;
??????}
??????batchSqlSession?=?sqlSessionFactory.openSession(ExecutorType.BATCH,?false);
??????for?(int?index?=?0;?index?????????mapper實例對象.更新/插入Method(accountDate,?data.get(index).getOrderNo());
????????if?(index?!=?0?&&?index?%?BATCH?==?0)?{
??????????batchSqlSession.commit();
??????????batchSqlSession.clearCache();
????????}
??????}
??????batchSqlSession.commit();
????}?catch?(Exception?e)?{
??????batchSqlSession.rollback();
??????log.error(e.getMessage(),?e);
????}?finally?{
??????if?(batchSqlSession?!=?null)?{
????????batchSqlSession.close();
??????}
????}
??}
你真的懂commit、clearCache、flushStatements嘛?

clearCache,我們先來看看commit到底都做了一些什么,以下為調(diào)用鏈??@Override
??public?void?commit()?{
????commit(false);
??}??
??@Override
??public?void?commit(boolean?force)?{
????try?{
??????executor.commit(isCommitOrRollbackRequired(force));
??????dirty?=?false;
????}?catch?(Exception?e)?{
??????throw?ExceptionFactory.wrapException("Error?committing?transaction.??Cause:?"?+?e,?e);
????}?finally?{
??????ErrorContext.instance().reset();
????}
??}
??private?boolean?isCommitOrRollbackRequired(boolean?force)?{
????//?autoCommit默認為false,調(diào)用過插入、更新、刪除之后的dirty值為true
????return?(!autoCommit?&&?dirty)?||?force;
??}
??@Override
??public?void?commit(boolean?required)?throws?SQLException?{
????if?(closed)?{
??????throw?new?ExecutorException("Cannot?commit,?transaction?is?already?closed");
????}
????clearLocalCache();
????flushStatements();
????if?(required)?{
??????transaction.commit();
????}
??}
clearLocalCache這件事情,所以大可不必在commit后加上一句clearCache,而且clearCache是做了什么你又知道嘛?就擱這調(diào)用!!
flushStatements的作用,官網(wǎng)里也有詳細解釋:
INSERT、UPDATE、DELETE語句真正刷新到數(shù)據(jù)庫中。底層調(diào)用了JDBC的statement.executeBatch方法。BatchResult,真正的結(jié)果可以通過BatchResult中的getUpdateCounts方法獲取。UPDATE、INSERT、DELETE語句刷新到數(shù)據(jù)庫中。這一點去看BatchExecutor中的doQuery方法即可。反例
mybatis ExecutorType.BATCH?批處理,反例如下:
不具備通用性
版本2-初具雛形
import?lombok.extern.slf4j.Slf4j;
import?org.apache.ibatis.session.ExecutorType;
import?org.apache.ibatis.session.SqlSession;
import?org.apache.ibatis.session.SqlSessionFactory;
import?org.springframework.stereotype.Component;
import?javax.annotation.Resource;
import?java.util.List;
import?java.util.function.ToIntFunction;
@Slf4j
@Component
public?class?MybatisBatchUtils?{
????/**
?????*?每次處理1000條
?????*/
????private?static?final?int?BATCH?=?1000;
????@Resource
????private?SqlSessionFactory?sqlSessionFactory;
????/**
?????*?批量處理修改或者插入
?????*
?????*?@param?data?????需要被處理的數(shù)據(jù)
?????*?@param?function?自定義處理邏輯
?????*?@return?int?影響的總行數(shù)
?????*/
????public???int?batchUpdateOrInsert(List ?data,?ToIntFunction ?{?function)
????????int?count?=?0;
????????SqlSession?batchSqlSession?=?sqlSessionFactory.openSession(ExecutorType.BATCH);
????????try?{
????????????for?(int?index?=?0;?index?????????????????count?+=?function.applyAsInt(data.get(index));
????????????????if?(index?!=?0?&&?index?%?BATCH?==?0)?{
????????????????????batchSqlSession.flushStatements();
????????????????}
????????????}
????????????batchSqlSession.commit();
????????}?catch?(Exception?e)?{
????????????batchSqlSession.rollback();
????????????log.error(e.getMessage(),?e);
????????}?finally?{
????????????batchSqlSession.close();
????????}
????????return?count;
????}
}
@Resource
private?某Mapper類?mapper實例對象;
batchUtils.batchUpdateOrInsert(數(shù)據(jù)集合,?item?->?mapper實例對象.insert方法(item));
版本3-標準寫法
BatchExecutor執(zhí)行器,我們知道每個SqlSession都會擁有一個Executor對象,這個對象才是執(zhí)行 SQL 語句的幕后黑手,我們也知道Spring跟Mybatis整合的時候使用的SqlSession是SqlSessionTemplate,默認用的是ExecutorType.SIMPLE,這個時候你通過自動注入獲得的Mapper對象其實是沒有開啟批處理的??public?Executor?newExecutor(Transaction?transaction,?ExecutorType?executorType)?{
????executorType?=?executorType?==?null???defaultExecutorType?:?executorType;
????executorType?=?executorType?==?null???ExecutorType.SIMPLE?:?executorType;
????Executor?executor;
????if?(ExecutorType.BATCH?==?executorType)?{
??????executor?=?new?BatchExecutor(this,?transaction);
????}?else?if?(ExecutorType.REUSE?==?executorType)?{
??????executor?=?new?ReuseExecutor(this,?transaction);
????}?else?{
??????executor?=?new?SimpleExecutor(this,?transaction);
????}
????if?(cacheEnabled)?{
??????executor?=?new?CachingExecutor(executor);
????}
????executor?=?(Executor)?interceptorChain.pluginAll(executor);
????return?executor;
??}
sqlSessionFactory.openSession(ExecutorType.BATCH)得到的sqlSession對象(此時里面的Executor是BatchExecutor)去獲得一個新的Mapper對象才能生效!!!MapperClass也一塊傳遞進來public?class?MybatisBatchUtils?{
????
????/**
????*?每次處理1000條
????*/
????private?static?final?int?BATCH_SIZE?=?1000;
????
????@Resource
????private?SqlSessionFactory?sqlSessionFactory;
????
????/**
????*?批量處理修改或者插入
????*
????*?@param?data?????需要被處理的數(shù)據(jù)
????*?@param?mapperClass??Mybatis的Mapper類
????*?@param?function?自定義處理邏輯
????*?@return?int?影響的總行數(shù)
????*/
????public???int?batchUpdateOrInsert(List ?data,?Class?mapperClass,?BiFunction ?{?function)
????????int?i?=?1;
????????SqlSession?batchSqlSession?=?sqlSessionFactory.openSession(ExecutorType.BATCH);
????????try?{
????????????U?mapper?=?batchSqlSession.getMapper(mapperClass);
????????????int?size?=?data.size();
????????????for?(T?element?:?data)?{
????????????????function.apply(element,mapper);
????????????????if?((i?%?BATCH_SIZE?==?0)?||?i?==?size)?{
????????????????????batchSqlSession.flushStatements();
????????????????}
????????????????i++;
????????????}
????????????//?非事務(wù)環(huán)境下強制commit,事務(wù)情況下該commit相當于無效
????????????batchSqlSession.commit(!TransactionSynchronizationManager.isSynchronizationActive());
????????}?catch?(Exception?e)?{
????????????batchSqlSession.rollback();
????????????throw?new?CustomException(e);
????????}?finally?{
????????????batchSqlSession.close();
????????}
????????return?i?-?1;
????}
}
batchUtils.batchUpdateOrInsert(數(shù)據(jù)集合,?xxxxx.class,?(item,?mapper實例對象)?->?mapper實例對象.insert方法(item));
附:Oracle批量插入優(yōu)化
Mybatis Generator生成的模板代碼中,insert的id是這樣獲取的<selectKey?keyProperty="id"?order="BEFORE"?resultType="java.lang.Long">
??select?XXX.nextval?from?dual
selectKey>
<insert?id="insert"?parameterType="user">
????????insert?into?table_name(id,?username,?password)
????????values(SEQ_USER.NEXTVAL,#{username},#{password})
insert>
推薦閱讀:
內(nèi)容包含Java基礎(chǔ)、JavaWeb、MySQL性能優(yōu)化、JVM、鎖、百萬并發(fā)、消息隊列、高性能緩存、反射、Spring全家桶原理、微服務(wù)、Zookeeper......等技術(shù)棧!
?戳閱讀原文領(lǐng)取!? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??朕已閱?
評論
圖片
表情

