您好,登錄后才能下訂單哦!
首先我先解釋一下標(biāo)題 四大對象是指:executor, statementHandler,parameterHandler,resultHandler對象。(為了方便下面的文章說道四大對象就專指它們)
它們都是sqlSession的底層類實現(xiàn),也是插件能夠攔截的四大對象。所以這里已經(jīng)觸及了MyBATIS的底層,動態(tài)代理,反射隨時可以看到,如果沒有第一篇作為基礎(chǔ),你將十分難以理解它。了解他們的協(xié)作,是插件編寫的基礎(chǔ)之一,所以這是十分的重要。
Executor在sqlSession中的應(yīng)用
上篇我們談到了一個問題,一個mapper被執(zhí)行是通過動態(tài)代理來完成的,然后進入到了sqlSession的方法中去。這個并不難理解,但是sqlSession內(nèi)部是怎么運行的呢?答案四大對象的協(xié)作。在SqlSession它還是一個接口,mybatis內(nèi)部是通過DefaultSqlSession這個實現(xiàn)類為我們提供服務(wù)的,它比較長,但是我們不需要全部看到,我們只看到很常用的selectList方法便可以了。
package org.apache.ibatis.session.defaults; public class DefaultSqlSession implements SqlSession { private Configuration configuration; private Executor executor; private boolean autoCommit; private boolean dirty; ....... @Override public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) { try { MappedStatement ms = configuration.getMappedStatement(statement); return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER); } catch (Exception e) { throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e); } finally { ErrorContext.instance().reset(); } } ...... }
我們可以看到它是通過executor去執(zhí)行方法來完成查詢的。
初認(rèn)Executor
那么我們對executor就很感興趣,于是我們看看executor是怎么樣的,首先在MyBATIS中有三種executor:
SimpleExecutor -- SIMPLE 就是普通的執(zhí)行器。
ReuseExecutor -執(zhí)行器會重用預(yù)處理語句(prepared statements)
BatchExecutor --它是批量執(zhí)行器
這些就是mybatis的三種執(zhí)行器。你可以通過配置文件的settings里面的元素defaultExecutorType,配置它,默認(rèn)是采用SimpleExecutor如果你在Spring運用它,那么你可以這么配置它:
<bean id="sqlSessionTemplateBatch" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> <!--更新采用批量的executor --> <constructor-arg index="1" value="BATCH"/> </bean>
這樣,它便是一個批量的執(zhí)行器。mybatis的三個executor都有一個共同的父類——BaseExecutor。
Executor初始化
首先我們先了解一下mybatis是怎么樣生成executor的。我們看到生成Executor的地方(org.apache.ibatis.session.Configuration):
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; }
這里大部分都很好理解,但是有個地方就好不好理解,它就是:
executor = (Executor) interceptorChain.pluginAll(executor);
這是一段非常重要的代碼,它是采用責(zé)任鏈模式,來產(chǎn)生代理對象。我們需要再深入理解它,打開它具體的pluginAll方法:
public Object pluginAll(Object target) { for (Interceptor interceptor : interceptors) { target = interceptor.plugin(target); } return target; }
我們這里先介紹一下這段代碼:
Interceptor它是mybatis攔截器必須要實現(xiàn)的接口,換句話說,這個遍歷就是遍歷mybatis的攔截器。
然后調(diào)用plugin方法,這個方法是為了生成代理對象(占位)的。
于是可以想象我們的插件的代理對象將會是一層層的嵌套,所以當(dāng)中任何一個插件(Interceptor)都有機會攔截這個真是的服務(wù)對象(executor),則便是責(zé)任鏈模式,我們完全可以提供插件(Interceptor),進入到代理對象的invoke方法里面,來改變executor的行為和方法。
但是我要在這里強調(diào),當(dāng)你使用插件的時候,你將改變mybatis的executor內(nèi)容實現(xiàn),你必須慎重的使用它。
如果要我們自己編寫動態(tài)的代理,那么工作量可不小,好在mybatis為我們提供了Plugin.java類來完成我們所需要的功能。
public class Plugin implements InvocationHandler { private Object target; private Interceptor interceptor; private Map<Class<?>, Set<Method>> signatureMap; private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) { this.target = target; this.interceptor = interceptor; this.signatureMap = signatureMap; } public static Object wrap(Object target, Interceptor interceptor) { Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor); Class<?> type = target.getClass(); Class<?>[] interfaces = getAllInterfaces(type, signatureMap); if (interfaces.length > 0) { return Proxy.newProxyInstance( type.getClassLoader(), interfaces, new Plugin(target, interceptor, signatureMap)); } return target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { Set<Method> methods = signatureMap.get(method.getDeclaringClass()); if (methods != null && methods.contains(method)) { return interceptor.intercept(new Invocation(target, method, args)); } return method.invoke(target, args); } catch (Exception e) { throw ExceptionUtil.unwrapThrowable(e); } } ...... }
這里有一個wrap方法:它會為我們生成代理對象。一旦我們的插件和它綁定,那么我們可以想到就會進入invoke方法里面。
invoke方法:很簡單,它運行首先通過class和method的過濾,看看是否需要攔截這個方法,如果被攔截,那么它就運行interceptor的intercept方法。所以當(dāng)我們配置了簽名,就能夠攔截我們的方法。
我們先討論那么多,我們知道后面講插件的時候我們還會提及它,這里我們知道它會根據(jù)插件的個數(shù)生成一層層的代理對象就可以了。
executor的執(zhí)行
executor的執(zhí)行是依賴于Statement對象來操作的,讓我們以SimpleExecutor的doQuery方法為例子:
public class SimpleExecutor extends BaseExecutor { ...... @Override public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException { Statement stmt = null; try { Configuration configuration = ms.getConfiguration(); StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql); stmt = prepareStatement(handler, ms.getStatementLog()); return handler.<E>query(stmt, resultHandler); } finally { closeStatement(stmt); } } ...... private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException { Statement stmt; Connection connection = getConnection(statementLog); stmt = handler.prepare(connection); handler.parameterize(stmt); return stmt; } }
很顯然這里調(diào)度的是一個查詢方法
首先它先生成StatementHandler對象。
通過prepareStatement方法調(diào)用prepare方法初始化參數(shù)。
然后使用parameterize方法設(shè)置參數(shù)到運行環(huán)境。
然后便通過handler.<E>query(stmt, resultHandler);方法來完成結(jié)果組裝。
于是我們的焦點就集中在了StatementHandler對象上,下章我們將談及它。
總結(jié)
以上所述是小編給大家介紹的Mybatis中SqlSession下的四大對象之執(zhí)行器(executor),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對億速云網(wǎng)站的支持!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。