這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān)Mybatis代理模塊有哪些以及如何執(zhí)行,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比西疇網(wǎng)站開(kāi)發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫(kù),直接使用。一站式西疇網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋西疇地區(qū)。費(fèi)用合理售后完善,十載實(shí)體公司更值得信賴。
在使用Mybatis的時(shí)候大家可能都有一個(gè)疑問(wèn),為什么只寫Mapper接口就能操作數(shù)據(jù)庫(kù)?
它的主要實(shí)現(xiàn)思想是:使用動(dòng)態(tài)代理生成實(shí)現(xiàn)類,然后配合x(chóng)ml的映射文件中的SQL語(yǔ)句來(lái)實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)的訪問(wèn)。
Mybatis是在iBatis上演變而來(lái)ORM框架,所以Mybatis最終會(huì)將代碼轉(zhuǎn)換成iBatis編程模型,而 Mybatis 代理階段主要是將面向接口編程模型,通過(guò)動(dòng)態(tài)代理轉(zhuǎn)換成ibatis編程模型。
我們不直接使用iBatis編程模型的原因是為了解耦,從下面的兩種示例我們可以看出,iBatis編程模型和配置文件耦合很嚴(yán)重。
@Test // 面向接口編程模型 public void quickStart() throws Exception { // 2.獲取sqlSession try (SqlSession sqlSession = sqlSessionFactory.openSession()) { initH2dbMybatis(sqlSession); // 3.獲取對(duì)應(yīng)mapper PersonMapper mapper = sqlSession.getMapper(PersonMapper.class); JdkProxySourceClassUtil.writeClassToDisk(mapper.getClass().getSimpleName(), mapper.getClass()); // 4.執(zhí)行查詢語(yǔ)句并返回結(jié)果 Person person = mapper.selectByPrimaryKey(1L); System.out.println(person.toString()); } }
@Test // ibatis編程模型 public void quickStartIBatis() throws Exception { // 2.獲取sqlSession try (SqlSession sqlSession = sqlSessionFactory.openSession()) { initH2dbMybatis(sqlSession); // ibatis編程模型(與配置文件耦合嚴(yán)重) Person person = sqlSession.selectOne("com.xiaolyuh.domain.mapper.PersonMapper.selectByPrimaryKey", 1L); System.out.println(person.toString()); } }
MapperRegistry:Mapper接口動(dòng)態(tài)代理工廠(MapperProxyFactory)的注冊(cè)中心
MapperProxyFactory:Mapper接口對(duì)應(yīng)的動(dòng)態(tài)代理工廠類。Mapper接口和MapperProxyFactory工廠類是一一對(duì)應(yīng)關(guān)系
MapperProxy:Mapper接口的增強(qiáng)器,它實(shí)現(xiàn)了InvocationHandler
接口,通過(guò)該增強(qiáng)的invoke方法實(shí)現(xiàn)了對(duì)數(shù)據(jù)庫(kù)的訪問(wèn)
MapperMethod:對(duì)insert, update, delete, select, flush節(jié)點(diǎn)方法的包裝類,它通過(guò)sqlSession
來(lái)完成了對(duì)數(shù)據(jù)庫(kù)的操作
在Mybatis 源碼(二)中我們會(huì)發(fā)現(xiàn)當(dāng)配置文件解析完成的最后一步是調(diào)用org.apache.ibatis.builder.xml.XMLMapperBuilder#bindMapperForNamespace
方法。該方法的主要作用是:根據(jù) namespace 屬性將Mapper接口的動(dòng)態(tài)代理工廠(MapperProxyFactory)注冊(cè)到 MapperRegistry 中。源碼如下:
private void bindMapperForNamespace() { // 獲取namespace屬性(對(duì)應(yīng)Mapper接口的全類名) String namespace = builderAssistant.getCurrentNamespace(); if (namespace != null) { Class<?> boundType = null; try { boundType = Resources.classForName(namespace); } catch (ClassNotFoundException e) { //ignore, bound type is not required } if (boundType != null) { // 防止重復(fù)加載 if (!configuration.hasMapper(boundType)) { // Spring may not know the real resource name so we set a flag // to prevent loading again this resource from the mapper interface // look at MapperAnnotationBuilder#loadXmlResource configuration.addLoadedResource("namespace:" + namespace); // 將Mapper接口的動(dòng)態(tài)代理工廠注冊(cè)到 MapperRegistry 中 configuration.addMapper(boundType); } } } }
讀取namespace屬性,獲取Mapper接口的全類名
根據(jù)全類名將Mapper接口加載到內(nèi)存
判斷是否重復(fù)加載Mapper接口
調(diào)用Mybatis 配置類(configuration)的addMapper方法,完成后續(xù)步驟
org.apache.ibatis.session.Configuration#addMapper
該方法直接回去調(diào)用org.apache.ibatis.binding.MapperRegistry#addMapper
方法完成注冊(cè)。
public <T> void addMapper(Class<T> type) { // 必須是接口 if (type.isInterface()) { if (hasMapper(type)) { // 防止重復(fù)注冊(cè) throw new BindingException("Type " + type + " is already known to the MapperRegistry."); } boolean loadCompleted = false; try { // 根據(jù)接口類,創(chuàng)建MapperProxyFactory代理工廠類 knownMappers.put(type, new MapperProxyFactory<>(type)); // It's important that the type is added before the parser is run // otherwise the binding may automatically be attempted by the // mapper parser. If the type is already known, it won't try. MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type); parser.parse(); loadCompleted = true; } finally { // 如果加載出現(xiàn)異常需要移除對(duì)應(yīng)Mapper if (!loadCompleted) { knownMappers.remove(type); } } } }
判斷加載類型是否是接口
重復(fù)注冊(cè)校驗(yàn),如果校驗(yàn)不通拋出BindingException
異常
根據(jù)接口類,創(chuàng)建MapperProxyFactory代理工廠類
如果加載出現(xiàn)異常需要移除對(duì)應(yīng)Mapper
在Mybatis 源碼(一)的快速開(kāi)始中有如下代碼,通過(guò) sqlSession獲取Mapper的代理對(duì)象:
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
sqlSession.getMapper(PersonMapper.class)
最終調(diào)用的是org.apache.ibatis.binding.MapperRegistry#getMapper
方法,最后返回的是PersonMapper
接口的代理對(duì)象,源碼如下:
public <T> T getMapper(Class<T> type, SqlSession sqlSession) { // 根據(jù)類型獲取對(duì)應(yīng)的代理工廠 final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type); if (mapperProxyFactory == null) { throw new BindingException("Type " + type + " is not known to the MapperRegistry."); } try { // 根據(jù)工廠類新建一個(gè)代理對(duì)象,并返回 return mapperProxyFactory.newInstance(sqlSession); } catch (Exception e) { throw new BindingException("Error getting mapper instance. Cause: " + e, e); } }
根據(jù)類型獲取對(duì)應(yīng)的代理工廠
根據(jù)工廠類新建一個(gè)代理對(duì)象,并返回
每一個(gè)Mapper接口對(duì)應(yīng)一個(gè)MapperProxyFactory工廠類。 MapperProxyFactory通過(guò)JDK動(dòng)態(tài)代理創(chuàng)建代理對(duì)象,Mapper接口的代理對(duì)象是方法級(jí)別,所以每次訪問(wèn)數(shù)據(jù)庫(kù)都需要新創(chuàng)建代理對(duì)象。源碼如下:
protected T newInstance(MapperProxy<T> mapperProxy) { // 使用JDK動(dòng)態(tài)代理生成代理實(shí)例 return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy); } public T newInstance(SqlSession sqlSession) { // Mapper的增強(qiáng)器 final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache); return newInstance(mapperProxy); }
先獲取Mapper對(duì)應(yīng)增強(qiáng)器(MapperProxy)
根據(jù)增強(qiáng)器使用JDK動(dòng)態(tài)代理產(chǎn)生代理對(duì)象
import com.sun.proxy..Proxy8; import com.xiaolyuh.domain.model.Person; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.lang.reflect.UndeclaredThrowableException; public final class $Proxy8 extends Proxy implements Proxy8 { private static Method m3; ... public $Proxy8(InvocationHandler var1) throws { super(var1); } ... public final Person selectByPrimaryKey(Long var1) throws { try { return (Person)super.h.invoke(this, m3, new Object[]{var1}); } catch (RuntimeException | Error var3) { throw var3; } catch (Throwable var4) { throw new UndeclaredThrowableException(var4); } } static { try { m3 = Class.forName("com.sun.proxy.$Proxy8").getMethod("selectByPrimaryKey", Class.forName("java.lang.Long")); } catch (NoSuchMethodException var2) { throw new NoSuchMethodError(var2.getMessage()); } catch (ClassNotFoundException var3) { throw new NoClassDefFoundError(var3.getMessage()); } } }
從代理類的反編譯結(jié)果來(lái)看,都是直接調(diào)用增強(qiáng)器的invoke
方法,進(jìn)而實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)的訪問(wèn)。
通過(guò)上訴反編譯代理對(duì)象,我們可以發(fā)現(xiàn)所有對(duì)數(shù)據(jù)庫(kù)的訪問(wèn)都是在增強(qiáng)器org.apache.ibatis.binding.MapperProxy#invoke
中實(shí)現(xiàn)的。
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { // 如果是Object本身的方法不增強(qiáng) if (Object.class.equals(method.getDeclaringClass())) { return method.invoke(this, args); } // 判斷是否是默認(rèn)方法 else if (method.isDefault()) { if (privateLookupInMethod == null) { return invokeDefaultMethodJava8(proxy, method, args); } else { return invokeDefaultMethodJava9(proxy, method, args); } } } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } // 從緩存中獲取MapperMethod對(duì)象 final MapperMethod mapperMethod = cachedMapperMethod(method); // 執(zhí)行MapperMethod return mapperMethod.execute(sqlSession, args); }
如果是Object本身的方法不增強(qiáng)
判斷是否是默認(rèn)方法
從緩存中獲取MapperMethod對(duì)象
執(zhí)行MapperMethod
MapperMethod
封裝了Mapper接口中對(duì)應(yīng)方法的信息(MethodSignature),以及對(duì)應(yīng)的sql語(yǔ)句的信息(SqlCommand);它是mapper接口與映射配置文件中sql語(yǔ)句的橋梁; MapperMethod對(duì)象不記錄任何狀態(tài)信息,所以它可以在多個(gè)代理對(duì)象之間共享;
SqlCommand : 從configuration中獲取方法的命名空間.方法名以及SQL語(yǔ)句的類型;
MethodSignature:封裝mapper接口方法的相關(guān)信息(入?yún)?,返回類型)?/p>
ParamNameResolver: 解析mapper接口方法中的入?yún)ⅲ?/p>
public Object execute(SqlSession sqlSession, Object[] args) { Object result; // 根據(jù)SQL類型,調(diào)用不同方法。 // 這里我們可以看出,操作數(shù)據(jù)庫(kù)都是通過(guò) sqlSession 來(lái)實(shí)現(xiàn)的 switch (command.getType()) { case INSERT: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.insert(command.getName(), param)); break; } case UPDATE: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.update(command.getName(), param)); break; } case DELETE: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.delete(command.getName(), param)); break; } case SELECT: // 根據(jù)方法返回值類型來(lái)確認(rèn)調(diào)用sqlSession的哪個(gè)方法 // 無(wú)返回值或者有結(jié)果處理器 if (method.returnsVoid() && method.hasResultHandler()) { executeWithResultHandler(sqlSession, args); result = null; } // 返回值是否為集合類型或數(shù)組 else if (method.returnsMany()) { result = executeForMany(sqlSession, args); } // 返回值是否為Map else if (method.returnsMap()) { result = executeForMap(sqlSession, args); } // 返回值是否為游標(biāo)類型 else if (method.returnsCursor()) { result = executeForCursor(sqlSession, args); } // 查詢單條記錄 else { // 參數(shù)解析 Object param = method.convertArgsToSqlCommandParam(args); result = sqlSession.selectOne(command.getName(), param); if (method.returnsOptional() && (result == null || !method.getReturnType().equals(result.getClass()))) { result = Optional.ofNullable(result); } } break; case FLUSH: result = sqlSession.flushStatements(); break; default: throw new BindingException("Unknown execution method for: " + command.getName()); } if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) { throw new BindingException("Mapper method '" + command.getName() + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ")."); } return result; } private <E> Object executeForMany(SqlSession sqlSession, Object[] args) { List<E> result; // 將方法參數(shù)轉(zhuǎn)換成SqlCommand參數(shù) Object param = method.convertArgsToSqlCommandParam(args); if (method.hasRowBounds()) { // 獲取分頁(yè)參數(shù) RowBounds rowBounds = method.extractRowBounds(args); result = sqlSession.selectList(command.getName(), param, rowBounds); } else { result = sqlSession.selectList(command.getName(), param); } // issue #510 Collections & arrays support if (!method.getReturnType().isAssignableFrom(result.getClass())) { if (method.getReturnType().isArray()) { return convertToArray(result); } else { return convertToDeclaredCollection(sqlSession.getConfiguration(), result); } } return result; }
在execute
方法中完成了面向接口編程模型到iBatis編程模型的轉(zhuǎn)換,轉(zhuǎn)換過(guò)程如下:
通過(guò)MapperMethod.SqlCommand. type
+MapperMethod.MethodSignature.returnType
來(lái)確定需要調(diào)用SqlSession
中的那個(gè)方法
通過(guò)MapperMethod.SqlCommand. name
來(lái)找到需要執(zhí)行方法的全類名
通過(guò)MapperMethod.MethodSignature.paramNameResolver
來(lái)轉(zhuǎn)換需要傳遞的參數(shù)
在Mybatis中SqlSession相當(dāng)于一個(gè)門面,所有對(duì)數(shù)據(jù)庫(kù)的操作都需要通過(guò)SqlSession接口,SqlSession中定義了所有對(duì)數(shù)據(jù)庫(kù)的操作方法,如數(shù)據(jù)庫(kù)讀寫命令、獲取映射器、管理事務(wù)等,也是Mybatis中為數(shù)不多的有注釋的類。
通過(guò)上面的源碼解析,可以發(fā)現(xiàn)Mybatis面向接口編程是通過(guò)JDK動(dòng)態(tài)代理模式來(lái)實(shí)現(xiàn)的。主要執(zhí)行流程是:
在映射文件初始化完成后,將對(duì)應(yīng)的Mapper接口的代理工廠類MapperProxyFactory
注冊(cè)到MapperRegistry
每次操作數(shù)據(jù)庫(kù)時(shí),sqlSession
通過(guò)MapperProxyFactory
獲取Mapper接口的代理類
代理類通過(guò)增強(qiáng)器MapperProxy
調(diào)用XML映射文件中SQL節(jié)點(diǎn)的封裝類MapperMethod
通過(guò)MapperMethod
將Mybatis 面向接口的編程模型轉(zhuǎn)換成iBatis編程模型(SqlSession模型)
通過(guò)SqlSession
完成對(duì)數(shù)據(jù)庫(kù)的操作
上述就是小編為大家分享的Mybatis代理模塊有哪些以及如何執(zhí)行了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
文章題目:Mybatis代理模塊有哪些以及如何執(zhí)行
鏈接地址:http://jinyejixie.com/article24/iicoce.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供商城網(wǎng)站、建站公司、網(wǎng)頁(yè)設(shè)計(jì)公司、企業(yè)建站、外貿(mào)建站、手機(jī)網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)