當前位置:
首頁 > 知識 > MyBatis源碼解讀之延遲載入 頂

MyBatis源碼解讀之延遲載入 頂

1. 目的

本文主要解讀MyBatis 延遲載入實現原理

2. 延遲載入如何使用

Setting 參數配置

設置參數描述有效值默認值lazyLoadingEnabled延遲載入的全局開關。當開啟時,所有關聯對象都會延遲載入。 特定關聯關係中可通過設置fetchType屬性來覆蓋該項的開關狀態。true、falsefalseaggressiveLazyLoading當開啟時,任何方法的調用都會載入該對象的所有屬性。否則,每個屬性會按需載入(參考lazyLoadTriggerMethods).true、falsefalse (true in ≤3.4.1)lazyLoadTriggerMethods指定哪個對象的方法觸發一次延遲載入。用逗號分隔的方法列表。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>
<!-- 結果對象 -->
<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 實體對象

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

省略...
}

執行解析:

  • 調用getUser查詢數據,從查詢結果集解析數據到User對象,當數據解析到lazy1,lazy2,lazy3判斷需要執行關聯查詢
  • lazyLoadingEnabled=true,將創建lazy1,lazy2,lazy3對應的Proxy延遲執行對象lazyLoader,並保存
  • 當邏輯觸發lazyLoadTriggerMethods 對應的方法(equals,clone,hashCode,toString)則執行延遲載入
  • 如果aggressiveLazyLoading=true,只要觸發到對象任何的方法,就會立即載入所有屬性的載入

3. 延遲載入原理實現

延遲載入主要是通過動態代理的形式實現,通過代理攔截到指定方法,執行數據載入。

MyBatis延遲載入主要使用:Javassist,Cglib實現,類圖展示:

MyBatis源碼解讀之延遲載入 頂

4. 延遲載入源碼解析

Setting 配置載入:

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;
}

//省略...
}

延遲載入代理對象創建

DefaultResultSetHandler

//#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的代理實現基本相同,這裡主要介紹Javasisst

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);
}
}
}

5. 注意事項

  1. IDEA調試問題 當配置aggressiveLazyLoading=true,在使用IDEA進行調試的時候,如果斷點打到代理執行邏輯當中,你會發現延遲載入的代碼永遠都不能進入,總是會被提前執行。 主要產生的原因在aggressiveLazyLoading,因為在調試的時候,IDEA的Debuger窗體中已經觸發了延遲載入對象的方法。

如圖:調試還未進入lazyLoader.loadAll(); 實際日誌已經顯示延遲載入已經完成,代碼與日誌通過顏色區分。

MyBatis源碼解讀之延遲載入 頂

6. 參考資料

本博客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源碼解讀之延遲載入就介紹到這裡。如有疑問,歡迎留言,謝謝。


喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

c 操作圖片存入xml和顯示圖片
計算機網路基礎知識總結

TAG:程序員小新人學習 |