本文主要解讀MyBatis 延遲加載實現原理html
Setting 參數配置git
設置參數 | 描述 | 有效值 | 默認值 |
---|---|---|---|
lazyLoadingEnabled | 延遲加載的全局開關。當開啓時,全部關聯對象都會延遲加載。 特定關聯關係中可經過設置fetchType屬性來覆蓋該項的開關狀態。 | true、false | false |
aggressiveLazyLoading | 當開啓時,任何方法的調用都會加載該對象的全部屬性。不然,每一個屬性會按需加載(參考lazyLoadTriggerMethods). | true、false | false (true in ≤3.4.1) |
lazyLoadTriggerMethods | 指定哪一個對象的方法觸發一次延遲加載。 | 用逗號分隔的方法列表。 | equals,clone,hashCode,toString |
配置github
<configuration> <settings> <!-- 開啓延遲加載 --> <setting name="lazyLoadingEnabled" value="true" /> <setting name="aggressiveLazyLoading" value="false" /> <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString" /> </settings> </configuration>
Mapper 配置spring
<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> <!-- 結果對象 --> <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> <!-- 執行的查詢 --> <select id="getUser" resultMap="userWithLazyProperties"> select * from users where id = #{id} </select> </mapper>
User 實體對象apache
public class User implements Cloneable { private Integer id; private String name; private User lazy1; private User lazy2; private List<User> lazy3; public int setterCounter; 省略... }
執行解析:mybatis
- 調用getUser查詢數據,從查詢結果集解析數據到User對象,當數據解析到lazy1,lazy2,lazy3判斷須要執行關聯查詢
- lazyLoadingEnabled=true,將建立lazy1,lazy2,lazy3對應的Proxy延遲執行對象lazyLoader,並保存
- 當邏輯觸發lazyLoadTriggerMethods 對應的方法(equals,clone,hashCode,toString)則執行延遲加載
- 若是aggressiveLazyLoading=true,只要觸發到對象任何的方法,就會當即加載全部屬性的加載
延遲加載主要是經過動態代理的形式實現,經過代理攔截到指定方法,執行數據加載。app
MyBatis延遲加載主要使用:Javassist,Cglib實現,類圖展現:ide
public class Configuration { /** aggressiveLazyLoading: * 當開啓時,任何方法的調用都會加載該對象的全部屬性。不然,每一個屬性會按需加載(參考lazyLoadTriggerMethods). * 默認爲true * */ protected boolean aggressiveLazyLoading; /** * 延遲加載觸發方法 */ protected Set<String> lazyLoadTriggerMethods = new HashSet<String>(Arrays.asList(new String[] { "equals", "clone", "hashCode", "toString" })); /** 是否開啓延遲加載 */ protected boolean lazyLoadingEnabled = false; /** * 默認使用Javassist代理工廠 * @param proxyFactory */ public void setProxyFactory(ProxyFactory proxyFactory) { if (proxyFactory == null) { proxyFactory = new JavassistProxyFactory(); } this.proxyFactory = proxyFactory; } //省略... }
DefaultResultSetHandlerfetch
//#mark 建立結果對象 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 建立返回的結果映射的真實對象 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 判斷屬性有沒配置嵌套查詢,若是有就建立代理對象 if (propertyMapping.getNestedQueryId() != null && propertyMapping.isLazy()) { //#mark 建立延遲加載代理對象 resultObject = configuration.getProxyFactory().createProxy(resultObject, lazyLoader, configuration, objectFactory, constructorArgTypes, constructorArgs); break; } } } this.useConstructorMappings = resultObject != null && !constructorArgTypes.isEmpty(); // set current mapping result return resultObject; }
因爲Javasisst和Cglib的代理實現基本相同,這裏主要介紹Javasisstui
ProxyFactory接口定義
public interface ProxyFactory { void setProperties(Properties properties); /** * 建立代理 * @param target 目標結果對象 * @param lazyLoader 延遲加載對象 * @param configuration 配置 * @param objectFactory 對象工廠 * @param constructorArgTypes 構造參數類型 * @param constructorArgs 構造參數值 * @return */ Object createProxy(Object target, ResultLoaderMap lazyLoader, Configuration configuration, ObjectFactory objectFactory, List<Class<?>> constructorArgTypes, List<Object> constructorArgs); }
JavasisstProxyFactory實現
public class JavassistProxyFactory implements org.apache.ibatis.executor.loader.ProxyFactory { /** * 接口實現 * @param target 目標結果對象 * @param lazyLoader 延遲加載對象 * @param configuration 配置 * @param objectFactory 對象工廠 * @param constructorArgTypes 構造參數類型 * @param constructorArgs 構造參數值 * @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); } //省略... /** * 代理對象實現,核心邏輯執行 */ private static class EnhancedResultObjectProxyImpl implements MethodHandler { /** * 建立代理對象 * @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) { //沒找到該方法,實現接口 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 { //建立新的代理對象 enhanced = enhancer.create(typesArray, valuesArray); } catch (Exception e) { throw new ExecutorException("Error creating lazy proxy. Cause: " + e, e); } //設置代理執行器 ((Proxy) enhanced).setHandler(callback); return enhanced; } /** * 代理對象執行 * @param enhanced 原對象 * @param method 原對象方法 * @param methodProxy 代理方法 * @param args 方法參數 * @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 { //延遲加載數量大於0 if (lazyLoader.size() > 0 && !FINALIZE_METHOD.equals(methodName)) { //aggressive 一次加載性全部須要要延遲加載屬性或者包含觸發延遲加載方法 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)) { //延遲加載單個屬性 lazyLoader.load(property); log.debug("load one :" + methodName); } } } } } return methodProxy.invoke(enhanced, args); } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } } }
如圖:調試還未進入lazyLoader.loadAll(); 實際日誌已經顯示延遲加載已經完成,代碼與日誌經過顏色區分。
本博客MyBatis源碼地址: - https://gitee.com/rainwen/mybatis
Java動態代理機制詳解(JDK 和CGLIB,Javassist,ASM) - http://blog.csdn.net/luanlouis/article/details/24589193
從類加載到動態編譯 - http://zhaoyw.cn/2017/07/classloader-dynamic
MyBatis 記錄二: lazy loading - http://yoncise.com/2016/11/05/MyBatis-%E8%AE%B0%E5%BD%95%E4%BA%8C-lazy-loading/
MyBatis官方文檔 - http://www.mybatis.org/mybatis-3/zh/index.html
MyBatis-Spring官方文檔 - http://www.mybatis.org/spring/zh/index.html
MyBatis-Spring源碼 - https://github.com/rainwen/spring
關於MyBatis源碼解讀之延遲加載就介紹到這裏。若有疑問,歡迎留言,謝謝。