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.a;> <resultMap type="org.a; id="user"> <id property="id" column="id" /> <result property="name" column="name" /> </resultMap> <!-- 结果对象 --> <resultMap type="org.a; 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实现,类图展示:
4. 延迟加载源码解析
Setting 配置加载:
public class Configuration { /** aggressiveLazyLoading: * 当开启时,任何方法的调用都会加载该对象的所有属性。否则,每个属性会按需加载(参考lazyLoadTriggerMethods). * 默认为true * */ protected boolean aggressiveLazyLoading; /** * 延迟加载触发方法 */ protected Set<String> lazyLoadTriggerMethods = new HashSet<String>(new String[] { "equals", "clone", "hashCode", "toString" })); /** 是否开启延迟加载 */ protected boolean lazyLoadingEnabled = false; /** * 默认使用Javassist代理工厂 * @param proxyFactory */ public void setProxyFactory(ProxyFactory proxyFactory) { if (proxyFactory == null) { proxyFactory = new JavassistProxyFactory(); } = proxyFactory; } //省略... }延迟加载代理对象创建
DefaultResultSetHandler
//#mark 创建结果对象 private Object createResultObject(ResultSetWrapper rsw, ResultMap resultMap, ResultLoaderMap lazyLoader, String columnPrefix) throws SQLException { = 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, re())) { final List<ResultMapping> propertyMappings = re(); for (ResultMapping propertyMapping : propertyMappings) { // issue gcode #109 && issue #149 判断属性有没配置嵌套查询,如果有就创建代理对象 if () != null && ()) { //#mark 创建延迟加载代理对象 resultObject = con().createProxy(resultObject, lazyLoader, configuration, objectFactory, constructorArgTypes, constructorArgs); break; } } } = resultObject != null && !con(); // 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.a { /** * 接口实现 * @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 En(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(); en(type); try { //通过获取对象方法,判断是否存在该方法 (WRITE_REPLACE_METHOD); // ObjectOutputStream will call writeReplace of objects returned by writeReplace if ()) { log.debug(WRITE_REPLACE_METHOD + " method was found on bean " + type + ", make sure it returns this"); } } catch (NoSuchMethodException e) { //没找到该方法,实现接口 en(new Class[]{Wri}); } catch (SecurityException e) { // nothing to do here } Object enhanced; Class<?>[] typesArray = con(new Class[con()]); Object[] valuesArray = con(new Object[con()]); try { //创建新的代理对象 enhanced = en(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 = me(); try { synchronized (lazyLoader) { if (methodName)) { //忽略暂未找到具体作用 Object original; if (con()) { original = objec(type); } else { original = objec(type, constructorArgTypes, constructorArgs); } Pro(type, enhanced, original); if () > 0) { return new JavassistSerialStateHolder(original, lazyLoader.getProperties(), objectFactory, constructorArgTypes, constructorArgs); } else { return original; } } else { //延迟加载数量大于0 if () > 0 && !FINALIZE_METHOD.equals(methodName)) { //aggressive 一次加载性所有需要要延迟加载属性或者包含触发延迟加载方法 if (aggressive || lazyLoadTriggerMe(methodName)) { log.debug("==> laze lod trigger method:" + methodName + ",proxy method:" + me() + " class:" + en()); //一次全部加载 lazyLoader.loadAll(); } else if (methodName)) { //判断是否为set方法,set方法不需要延迟加载 final String property = Pro(methodName); lazyLoader.remove(property); } else if (methodName)) { final String property = Pro(methodName); if (property)) { //延迟加载单个属性 lazyLoader.load(property); log.debug("load one :" + methodName); } } } } } return me(enhanced, args); } catch (Throwable t) { throw Exce(t); } } }5. 注意事项
- IDEA调试问题 当配置aggressiveLazyLoading=true,在使用IDEA进行调试的时候,如果断点打到代理执行逻辑当中,你会发现延迟加载的代码永远都不能进入,总是会被提前执行。 主要产生的原因在aggressiveLazyLoading,因为在调试的时候,IDEA的Debuger窗体中已经触发了延迟加载对象的方法。
如图:调试还未进入lazyLoader.loadAll(); 实际日志已经显示延迟加载已经完成,代码与日志通过颜色区分。