MyBatis 延遲加載針對嵌套查詢 (<collection>, <association>) 實現按需加載關聯數據。本文從配置方式、源碼級代理機制、aggressiveLazyLoading 預設行為陷阱、觸發條件自定義等維度深度解析。
<resultMap id="BaseResultMap" type="com.example.SysWfProcess">
<id column="id" property="id"/>
<collection property="nodes" column="id"
ofType="com.example.SysWfNode" select="selectNodes" fetchType="lazy"/>
</resultMap>
優先級最高,覆蓋全域設定。
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
</settings>
特定關聯需即時加載時,設定 fetchType="eager" 覆蓋。
DefaultResultSetHandler.createResultObject() 流程:
ResultMapping 中是否有 nestedQueryId != null && isLazy()ProxyFactory.createProxy() 建立實體對象的代理 (而非屬性代理)預設代理工廠:JavassistProxyFactory (需 javassist 依賴),可切換 CGLIB:
<setting name="proxyFactory" value="CGLIB"/>
預設行為:首次調用代理對象的任意方法 (包括 toString(), equals(), hashCode()) 即觸發所有延遲屬性加載。
// 測試代碼
SysWfProcess process = mapper.selectByPrimaryKey(1);
System.out.println(process.getClass()); // 僅打印類名,但觸發了 nodes 集合加載!
日誌顯示執行了兩條 SQL:主查詢 + 關聯查詢。這違背了「按需加載」初衷。
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
效果:僅在首次訪問具體延遲屬性時 (如 process.getNodes()) 觸發該屬性加載,其他屬性保持未加載 (null)。
關閉 aggressiveLazyLoading 後,仍可指定特定方法觸發全量加載:
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
預設即為這四個方法。可擴展如 init,loadAll 等業務方法。
public Object invoke(Object enhanced, Method method, Method methodProxy, Object[] args) {
String methodName = method.getName();
if (WRITE_REPLACE_METHOD.equals(methodName)) { /* 序列化處理 */ }
else {
if (lazyLoader.size() > 0 && !FINALIZE_METHOD.equals(methodName)) {
if (aggressive || lazyLoadTriggerMethods.contains(methodName)) {
lazyLoader.loadAll(); // 全量加載
} else if (PropertyNamer.isProperty(methodName)) {
String property = PropertyNamer.methodToProperty(methodName); // getNodes -> nodes
if (lazyLoader.hasLoader(property)) {
lazyLoader.load(property); // 單屬性加載
}
}
}
}
return methodProxy.invoke(enhanced, args);
}
關鍵點:攔截發生在目標方法執行前,保證屬性已加載再執行業務邏輯。
lazyLoadingEnabled=true, aggressiveLazyLoading=falseeager),哪些是低頻可選 (設 lazy)toString()、日誌輸出中直接引用實體對象,誤觸發全量加載JOIN 查詢或批次預加載理解代理機制與預設行為,才能真正駕馭 MyBatis 延遲加載,避免「以為延遲了,實則全載了」的效能陷阱。