热门标签 | HotTags
当前位置:  开发笔记 > 前端 > 正文

Mybatis懒加载的实现

这篇文章主要介绍了Mybatis懒加载的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

因为通过javassist和cglib代理实现的,所以说到底最主要的就是JavasisstProxyFactory类中的invoke方法和里面的load方法。

其实读一读,里面的逻辑就是跟配置中定义的规则一样的
因为github上的mybatis中文版中这部分注释比较少,所以从网上寻找博客,截取了代码注释片段记录下。
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> constructorArgTypes, List 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<&#63;> type, MethodHandler callback, List> constructorArgTypes, List 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<&#63;>[] 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);
  }
 }
 }

load方法

/**
  * 执行懒加载查询,获取数据并且set到userObject中返回
  * @param userObject
  * @throws SQLException
  */
 public void load(final Object userObject) throws SQLException {
  
  //合法性校验
  if (this.metaResultObject == null || this.resultLoader == null) {
  if (this.mappedParameter == null) {
   throw new ExecutorException("Property [" + this.property + "] cannot be loaded because "
     + "required parameter of mapped statement ["
     + this.mappedStatement + "] is not serializable.");
  }
  
  //获取mappedstatement并且校验
  final Configuration cOnfig= this.getConfiguration();
  final MappedStatement ms = config.getMappedStatement(this.mappedStatement);
  if (ms == null) {
   throw new ExecutorException("Cannot lazy load property [" + this.property
     + "] of deserialized object [" + userObject.getClass()
     + "] because configuration does not contain statement ["
     + this.mappedStatement + "]");
  }
 
  //使用userObject构建metaobject,并且重新构建resultloader对象
  this.metaResultObject = config.newMetaObject(userObject);
  this.resultLoader = new ResultLoader(config, new ClosedExecutor(), ms, this.mappedParameter,
    metaResultObject.getSetterType(this.property), null, null);
  }
 
  /* We are using a new executor because we may be (and likely are) on a new thread
  * and executors aren't thread safe. (Is this sufficient&#63;)
  *
  * A better approach would be making executors thread safe. */
  if (this.serializatiOnCheck== null) {
  final ResultLoader old = this.resultLoader;
  this.resultLoader = new ResultLoader(old.configuration, new ClosedExecutor(), old.mappedStatement,
    old.parameterObject, old.targetType, old.cacheKey, old.boundSql);
  }
 
  //获取数据库查询结果并且set到结果对象返回
  this.metaResultObject.setValue(property, this.resultLoader.loadResult());
 }

参考地址:
https://www.cnblogs.com/qixidi/p/10251126.html
https://blog.csdn.net/mingtian625/article/details/47358003

到此这篇关于Mybatis懒加载的实现的文章就介绍到这了,更多相关Mybatis 懒加载内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!


推荐阅读
  • PHP 5.2.5 安装与配置指南
    本文详细介绍了 PHP 5.2.5 的安装和配置步骤,帮助开发者解决常见的环境配置问题,特别是上传图片时遇到的错误。通过本教程,您可以顺利搭建并优化 PHP 运行环境。 ... [详细]
  • 构建基于BERT的中文NL2SQL模型:一个简明的基准
    本文探讨了将自然语言转换为SQL语句(NL2SQL)的任务,这是人工智能领域中一项非常实用的研究方向。文章介绍了笔者在公司举办的首届中文NL2SQL挑战赛中的实践,该比赛提供了金融和通用领域的表格数据,并标注了对应的自然语言与SQL语句对,旨在训练准确的NL2SQL模型。 ... [详细]
  • 数据库内核开发入门 | 搭建研发环境的初步指南
    本课程将带你从零开始,逐步掌握数据库内核开发的基础知识和实践技能,重点介绍如何搭建OceanBase的开发环境。 ... [详细]
  • 本文深入探讨 MyBatis 中动态 SQL 的使用方法,包括 if/where、trim 自定义字符串截取规则、choose 分支选择、封装查询和修改条件的 where/set 标签、批量处理的 foreach 标签以及内置参数和 bind 的用法。 ... [详细]
  • 扫描线三巨头 hdu1928hdu 1255  hdu 1542 [POJ 1151]
    学习链接:http:blog.csdn.netlwt36articledetails48908031学习扫描线主要学习的是一种扫描的思想,后期可以求解很 ... [详细]
  • This document outlines the recommended naming conventions for HTML attributes in Fast Components, focusing on readability and consistency with existing standards. ... [详细]
  • PHP 5.5.0rc1 发布:深入解析 Zend OPcache
    2013年5月9日,PHP官方发布了PHP 5.5.0rc1和PHP 5.4.15正式版,这两个版本均支持64位环境。本文将详细介绍Zend OPcache的功能及其在Windows环境下的配置与测试。 ... [详细]
  • 本文介绍如何在Java项目中使用Log4j库进行日志记录。我们将详细说明Log4j库的引入、配置及简单应用,帮助开发者快速上手。 ... [详细]
  • 本文详细介绍了如何在ECharts中使用线性渐变色,通过echarts.graphic.LinearGradient方法实现。文章不仅提供了完整的代码示例,还解释了各个参数的具体含义及其应用场景。 ... [详细]
  • 基于KVM的SRIOV直通配置及性能测试
    SRIOV介绍、VF直通配置,以及包转发率性能测试小慢哥的原创文章,欢迎转载目录?1.SRIOV介绍?2.环境说明?3.开启SRIOV?4.生成VF?5.VF ... [详细]
  • 本文详细介绍了Git分布式版本控制系统中远程仓库的概念和操作方法。通过具体案例,帮助读者更好地理解和掌握如何高效管理代码库。 ... [详细]
  • QBlog开源博客系统:Page_Load生命周期与参数传递优化(第四部分)
    本教程将深入探讨QBlog开源博客系统的Page_Load生命周期,并介绍一种简洁的参数传递重构方法。通过视频演示和详细讲解,帮助开发者更好地理解和应用这些技术。 ... [详细]
  • 精选30本C# ASP.NET SQL中文PDF电子书合集
    欢迎订阅我们的技术博客,获取更多关于C#、ASP.NET和SQL的最新资讯和资源。 ... [详细]
  • Hadoop入门与核心组件详解
    本文详细介绍了Hadoop的基础知识及其核心组件,包括HDFS、MapReduce和YARN。通过本文,读者可以全面了解Hadoop的生态系统及应用场景。 ... [详细]
  • 深入解析三大范式与JDBC集成
    本文详细探讨了数据库设计中的三大范式,并结合Java数据库连接(JDBC)技术,讲解如何在实际开发中应用这些概念。通过实例和图表,帮助读者更好地理解范式理论及其在数据操作中的重要性。 ... [详细]
author-avatar
愤怒的黑皮_165
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有