久久综合九色综合97婷婷-美女视频黄频a免费-精品日本一区二区三区在线观看-日韩中文无码有码免费视频-亚洲中文字幕无码专区-扒开双腿疯狂进出爽爽爽动态照片-国产乱理伦片在线观看夜-高清极品美女毛茸茸-欧美寡妇性猛交XXX-国产亚洲精品99在线播放-日韩美女毛片又爽又大毛片,99久久久无码国产精品9,国产成a人片在线观看视频下载,欧美疯狂xxxx吞精视频

有趣生活

當(dāng)前位置:首頁>職場>mybatis延遲加載原理(mybatis工作原理及流程)

mybatis延遲加載原理(mybatis工作原理及流程)

發(fā)布時(shí)間:2024-01-24閱讀(15)

導(dǎo)讀1.目的本文主要解讀MyBatis延遲加載實(shí)現(xiàn)原理2.延遲加載如何使用Setting參數(shù)配置設(shè)置參數(shù)描述有效值默認(rèn)值lazyLoadingEnabled延遲....

1. 目的

本文主要解讀MyBatis 延遲加載實(shí)現(xiàn)原理

2. 延遲加載如何使用

Setting 參數(shù)配置

設(shè)置參數(shù)描述有效值默認(rèn)值lazyLoadingEnabled延遲加載的全局開關(guān)。當(dāng)開啟時(shí),所有關(guān)聯(lián)對象都會(huì)延遲加載。 特定關(guān)聯(lián)關(guān)系中可通過設(shè)置fetchType屬性來覆蓋該項(xiàng)的開關(guān)狀態(tài)。true、falsefalseaggressiveLazyLoading當(dāng)開啟時(shí),任何方法的調(diào)用都會(huì)加載該對象的所有屬性。否則,每個(gè)屬性會(huì)按需加載(參考lazyLoadTriggerMethods).true、falsefalse (true in ≤3.4.1)lazyLoadTriggerMethods指定哪個(gè)對象的方法觸發(fā)一次延遲加載。用逗號分隔的方法列表。equals,clone,hashCode,toString

配置

<configuration> <settings> <!-- 開啟延遲加載 --> <setting name="lazyLoadingEnabled" value="true" /> <setting name="aggressiveLazyLoading" value="false" /> <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString" /> </settings></configuration>  

Mapper 配置

<mapper namespace="org.apache.ibatis.submitted.lazy_properties.Mapper">  <resultMap type="org.apache.ibatis.submitted.lazy_properties.User" id="user"> <id property="id" column="id" /> <result property="name" column="name" /> </resultMap> <!-- 結(jié)果對象 --> <resultMap type="org.apache.ibatis.submitted.lazy_properties.User" id="userWithLazyProperties" extends="user"> <!-- 延遲加載對象lazy1 --> <association property="lazy1" column="id" select="getLazy1" fetchType="lazy" /> <!-- 延遲加載對象lazy2 --> <association property="lazy2" column="id" select="getLazy2" fetchType="lazy" /> <!-- 延遲加載集合lazy3 -->  <collection property="lazy3" column="id" select="getLazy3" fetchType="lazy" /> </resultMap> <!-- 執(zhí)行的查詢 --> <select id="getUser" resultMap="userWithLazyProperties"> select * from users where id = #{id} </select></mapper>  

User 實(shí)體對象

public class User implements Cloneable { private Integer id; private String name; private User lazy1; private User lazy2; private List<User> lazy3; public int setterCounter;  省略... }  

執(zhí)行解析:

  • 調(diào)用getUser查詢數(shù)據(jù),從查詢結(jié)果集解析數(shù)據(jù)到User對象,當(dāng)數(shù)據(jù)解析到lazy1,lazy2,lazy3判斷需要執(zhí)行關(guān)聯(lián)查詢
  • lazyLoadingEnabled=true,將創(chuàng)建lazy1,lazy2,lazy3對應(yīng)的Proxy延遲執(zhí)行對象lazyLoader,并保存
  • 當(dāng)邏輯觸發(fā)lazyLoadTriggerMethods 對應(yīng)的方法(equals,clone,hashCode,toString)則執(zhí)行延遲加載
  • 如果aggressiveLazyLoading=true,只要觸發(fā)到對象任何的方法,就會(huì)立即加載所有屬性的加載

3. 延遲加載原理實(shí)現(xiàn)

延遲加載主要是通過動(dòng)態(tài)代理的形式實(shí)現(xiàn),通過代理攔截到指定方法,執(zhí)行數(shù)據(jù)加載。

MyBatis延遲加載主要使用:Javassist,Cglib實(shí)現(xiàn),類圖展示:

mybatis延遲加載原理(mybatis工作原理及流程)(1)

4. 延遲加載源碼解析

Setting 配置加載:

public class Configuration {/** aggressiveLazyLoading: * 當(dāng)開啟時(shí),任何方法的調(diào)用都會(huì)加載該對象的所有屬性。否則,每個(gè)屬性會(huì)按需加載(參考lazyLoadTriggerMethods). * 默認(rèn)為true * */ protected boolean aggressiveLazyLoading; /** * 延遲加載觸發(fā)方法 */ protected Set<String> lazyLoadTriggerMethods = new HashSet<String>(Arrays.asList(new String[] { "equals", "clone", "hashCode", "toString" })); /** 是否開啟延遲加載 */ protected boolean lazyLoadingEnabled = false;  /** * 默認(rèn)使用Javassist代理工廠 * @param proxyFactory */ public void setProxyFactory(ProxyFactory proxyFactory) { if (proxyFactory == null) { proxyFactory = new JavassistProxyFactory(); } this.proxyFactory = proxyFactory; }  //省略...}  

延遲加載代理對象創(chuàng)建

DefaultResultSetHandler

//#mark 創(chuàng)建結(jié)果對象 private Object createResultObject(ResultSetWrapper rsw, ResultMap resultMap, ResultLoaderMap lazyLoader, String columnPrefix) throws SQLException { this.useConstructorMappings = false; // reset previous mapping result final List<Class<?>> constructorArgTypes = new ArrayList<Class<?>>(); final List<Object> constructorArgs = new ArrayList<Object>(); //#mark 創(chuàng)建返回的結(jié)果映射的真實(shí)對象 Object resultObject = createResultObject(rsw, resultMap, constructorArgTypes, constructorArgs, columnPrefix); if (resultObject != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) { final List<ResultMapping> propertyMappings = resultMap.getPropertyResultMappings(); for (ResultMapping propertyMapping : propertyMappings) { // issue gcode #109 && issue #149 判斷屬性有沒配置嵌套查詢,如果有就創(chuàng)建代理對象 if (propertyMapping.getNestedQueryId() != null && propertyMapping.isLazy()) { //#mark 創(chuàng)建延遲加載代理對象 resultObject = configuration.getProxyFactory().createProxy(resultObject, lazyLoader, configuration, objectFactory, constructorArgTypes, constructorArgs); break; } } } this.useConstructorMappings = resultObject != null && !constructorArgTypes.isEmpty(); // set current mapping result return resultObject; }  

代理功能實(shí)現(xiàn)

由于Javasisst和Cglib的代理實(shí)現(xiàn)基本相同,這里主要介紹Javasisst

ProxyFactory接口定義

public interface ProxyFactory {

void setProperties(Properties properties);

/**

* 創(chuàng)建代理

* @param target 目標(biāo)結(jié)果對象

* @param lazyLoader 延遲加載對象

* @param configuration 配置

* @param objectFactory 對象工廠

* @param constructorArgTypes 構(gòu)造參數(shù)類型

* @param constructorArgs 構(gòu)造參數(shù)值

* @return

*/

Object createProxy(Object target, ResultLoaderMap lazyLoader, Configuration configuration, ObjectFactory objectFactory, List<Class<?>> constructorArgTypes, List<Object> constructorArgs);

}

JavasisstProxyFactory實(shí)現(xiàn)

public class JavassistProxyFactory implements org.apache.ibatis.executor.loader.ProxyFactory {  /** * 接口實(shí)現(xiàn) * @param target 目標(biāo)結(jié)果對象 * @param lazyLoader 延遲加載對象 * @param configuration 配置 * @param objectFactory 對象工廠 * @param constructorArgTypes 構(gòu)造參數(shù)類型 * @param constructorArgs 構(gòu)造參數(shù)值 * @return */ @Override public Object createProxy(Object target, ResultLoaderMap lazyLoader, Configuration configuration, ObjectFactory objectFactory, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) { return EnhancedResultObjectProxyImpl.createProxy(target, lazyLoader, configuration, objectFactory, constructorArgTypes, constructorArgs); } //省略...  /** * 代理對象實(shí)現(xiàn),核心邏輯執(zhí)行 */ private static class EnhancedResultObjectProxyImpl implements MethodHandler {  /** * 創(chuàng)建代理對象 * @param type * @param callback * @param constructorArgTypes * @param constructorArgs * @return */ static Object crateProxy(Class<?> type, MethodHandler callback, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) { ProxyFactory enhancer = new ProxyFactory(); enhancer.setSuperclass(type); try { //通過獲取對象方法,判斷是否存在該方法 type.getDeclaredMethod(WRITE_REPLACE_METHOD); // ObjectOutputStream will call writeReplace of objects returned by writeReplace if (log.isDebugEnabled()) { log.debug(WRITE_REPLACE_METHOD + " method was found on bean " + type + ", make sure it returns this"); } } catch (NoSuchMethodException e) { //沒找到該方法,實(shí)現(xiàn)接口 enhancer.setInterfaces(new Class[]{WriteReplaceInterface.class}); } catch (SecurityException e) { // nothing to do here } Object enhanced; Class<?>[] typesArray = constructorArgTypes.toArray(new Class[constructorArgTypes.size()]); Object[] valuesArray = constructorArgs.toArray(new Object[constructorArgs.size()]); try { //創(chuàng)建新的代理對象 enhanced = enhancer.create(typesArray, valuesArray); } catch (Exception e) { throw new ExecutorException("Error creating lazy proxy. Cause: " + e, e); } //設(shè)置代理執(zhí)行器 ((Proxy) enhanced).setHandler(callback); return enhanced; }   /** * 代理對象執(zhí)行 * @param enhanced 原對象 * @param method 原對象方法 * @param methodProxy 代理方法 * @param args 方法參數(shù) * @return * @throws Throwable */ @Override public Object invoke(Object enhanced, Method method, Method methodProxy, Object[] args) throws Throwable { final String methodName = method.getName(); try { synchronized (lazyLoader) { if (WRITE_REPLACE_METHOD.equals(methodName)) {  //忽略暫未找到具體作用 Object original; if (constructorArgTypes.isEmpty()) { original = objectFactory.create(type); } else { original = objectFactory.create(type, constructorArgTypes, constructorArgs); } PropertyCopier.copyBeanProperties(type, enhanced, original); if (lazyLoader.size() > 0) { return new JavassistSerialStateHolder(original, lazyLoader.getProperties(), objectFactory, constructorArgTypes, constructorArgs); } else { return original; } } else { //延遲加載數(shù)量大于0 if (lazyLoader.size() > 0 && !FINALIZE_METHOD.equals(methodName)) { //aggressive 一次加載性所有需要要延遲加載屬性或者包含觸發(fā)延遲加載方法 if (aggressive || lazyLoadTriggerMethods.contains(methodName)) { log.debug("==> laze lod trigger method:" + methodName + ",proxy method:" + methodProxy.getName() + " class:" + enhanced.getClass()); //一次全部加載 lazyLoader.loadAll(); } else if (PropertyNamer.isSetter(methodName)) { //判斷是否為set方法,set方法不需要延遲加載 final String property = PropertyNamer.methodToProperty(methodName); lazyLoader.remove(property); } else if (PropertyNamer.isGetter(methodName)) { final String property = PropertyNamer.methodToProperty(methodName); if (lazyLoader.hasLoader(property)) { //延遲加載單個(gè)屬性 lazyLoader.load(property); log.debug("load one :" + methodName); } } } } } return methodProxy.invoke(enhanced, args); } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } } }  

5. 注意事項(xiàng)

  1. IDEA調(diào)試問題 當(dāng)配置aggressiveLazyLoading=true,在使用IDEA進(jìn)行調(diào)試的時(shí)候,如果斷點(diǎn)打到代理執(zhí)行邏輯當(dāng)中,你會(huì)發(fā)現(xiàn)延遲加載的代碼永遠(yuǎn)都不能進(jìn)入,總是會(huì)被提前執(zhí)行。 主要產(chǎn)生的原因在aggressiveLazyLoading,因?yàn)樵谡{(diào)試的時(shí)候,IDEA的Debuger窗體中已經(jīng)觸發(fā)了延遲加載對象的方法。

如圖:調(diào)試還未進(jìn)入lazyLoader.loadAll(); 實(shí)際日志已經(jīng)顯示延遲加載已經(jīng)完成,代碼與日志通過顏色區(qū)分。

mybatis延遲加載原理(mybatis工作原理及流程)(2)
TAGS標(biāo)簽:  mybatis  延遲  加載  原理  mybatis延遲加  載原理(mybati

歡迎分享轉(zhuǎn)載→http://www.avcorse.com/read-252341.html

Copyright ? 2024 有趣生活 All Rights Reserve吉ICP備19000289號-5 TXT地圖HTML地圖XML地圖