MyBatis源码剖析之Mapper代理方式细节

2023-08-07 10:11:32

MyBatis是一个流行的Java持久层框架,它提供了多种方式来执行数据库操作,其中之一就是通过Mapper代理方式。通过Mapper代理方式,开发者可以编写接口,然后MyBatis会动态地生成接口的实现类,从而避免了繁琐的SQL映射配置。

具体代码如下:
*在这里插入图片描述*

思考⼀个问题,通常的Mapper接⼝我们都没有实现的⽅法却可以使⽤,是为什么呢?

答案很简单:动态代理

public class Configuration {  
    protected final MapperRegistry mapperRegistry = new MapperRegistry(this);
}

public class MapperRegistry {
  private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
}

开始之前介绍⼀下MyBatis初始化时对接⼝的处理:MapperRegistryConfiguration中的⼀个属性,它内部维护⼀个HashMap⽤于存放mapper接⼝的⼯⼚类,每个接⼝对应⼀个⼯⼚类。mappers中可以配置接⼝的包路径,或者某个具体的接⼝类。
在这里插入图片描述

当解析mappers标签时,它会判断解析到的是mapper配置⽂件时,会再将对应配置⽂件中的增删改查标签 封装成MappedStatement对象,存⼊mappedStatements中。当判断解析到接⼝时,会建此接⼝对应的MapperProxyFactory对象,存⼊HashMap中,key =接⼝的字节码对象,value =此接⼝对应MapperProxyFactory对象。

源码剖析-getmapper()

进⼊ sqlSession.getMapper(UserMapper.class )中

public interface SqlSession extends Closeable {
      //调用configuration中的getMapper
      <T> T getMapper(Class<T> type);
}

public class DefaultSqlSession implements SqlSession {
  @Override
  public <T> T getMapper(Class<T> type) {
    //调用configuration 中的getMapper
    return configuration.<T>getMapper(type, this);
  }
}

public class Configuration {
  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    //调用MapperRegistry 中的getMapper
    return mapperRegistry.getMapper(type, sqlSession);
  }
}

public class MapperRegistry {
  @SuppressWarnings("unchecked")
  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    //从 MapperRegistry 中的 HashMap 中拿 MapperProxyFactory
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    if (mapperProxyFactory == null) {
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
      //调用MapperProxyFactory的newInstance通过动态代理⼯⼚⽣成实例
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }
}


public class MapperProxyFactory<T> {
  public T newInstance(SqlSession sqlSession) {
    //创建了 JDK动态代理的Handler类
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    //调⽤了重载⽅法
    return newInstance(mapperProxy);
  }
   
  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }
}

//MapperProxy 类,实现了 InvocationHandler 接⼝
public class MapperProxy<T> implements InvocationHandler, Serializable {
  //省略部分源码
  private final SqlSession sqlSession;
  private final Class<T> mapperInterface;
  private final Map<Method, MapperMethod> methodCache;
    
  //构造,传⼊了 SqlSession,说明每个session中的代理对象的不同的!  
  public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
    this.sqlSession = sqlSession;
    this.mapperInterface = mapperInterface;
    this.methodCache = methodCache;
  }
  
   //省略部分源码
}

源码剖析-invoke()

在动态代理返回了示例后,我们就可以直接调⽤mapper类中的⽅法了,但代理对象调⽤⽅法,执⾏是在MapperProxy中的invoke⽅法中。

public class MapperProxy<T> implements InvocationHandler, Serializable { 
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      //如果是Object定义的⽅法,直接调⽤
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      } else if (isDefaultMethod(method)) {
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
    // 获得 MapperMethod 对象
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    //重点在这:最终调⽤了MapperMethod执⾏的⽅法
    return mapperMethod.execute(sqlSession, args);
  }
}

进⼊execute⽅法:

public class MapperMethod { 
  public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    //判断mapper中的⽅法类型,最终调⽤的还是SqlSession中的⽅法 switch(command.getType()) 
    switch (command.getType()) {
      case INSERT: {
        //转换参数
        Object param = method.convertArgsToSqlCommandParam(args);
        //执⾏INSERT操作
        //转换rowCount
        result = rowCountResult(sqlSession.insert(command.getName(), param));
        break;
      }
      case UPDATE: {
        //转换参数
        Object param = method.convertArgsToSqlCommandParam(args);
        // 转换 rowCount
        result = rowCountResult(sqlSession.update(command.getName(), param));
        break;
      }
      case DELETE: {
        //转换参数
        Object param = method.convertArgsToSqlCommandParam(args);
        // 转换 rowCount
        result = rowCountResult(sqlSession.delete(command.getName(), param));
        break;
      }
      case SELECT:
        //⽆返回,并且有ResultHandler⽅法参数,则将查询的结果,提交给 ResultHandler 进⾏处理
        if (method.returnsVoid() && method.hasResultHandler()) {
          executeWithResultHandler(sqlSession, args);
          result = null;
        //执⾏查询,返回列表
        } else if (method.returnsMany()) {
          result = executeForMany(sqlSession, args);
        //执⾏查询,返回Map
        } else if (method.returnsMap()) {
          result = executeForMap(sqlSession, args);
        //执⾏查询,返回Cursor
        } else if (method.returnsCursor()) {
          result = executeForCursor(sqlSession, args);
        //执⾏查询,返回单个对象
        } else {
          //转换参数
          Object param = method.convertArgsToSqlCommandParam(args);
          //查询单条
          result = sqlSession.selectOne(command.getName(), param);
        }
        break;
      case FLUSH:
        result = sqlSession.flushStatements();
        break;
      default:
        throw new BindingException("Unknown execution method for: " + command.getName());
    }
    //返回结果为null,并且返回类型为基本类型,则抛出BindingException异常
    if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
      throw new BindingException("Mapper method '" + command.getName() 
          + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
    }
    //返回结果
    return result;
  }
}

总的来说,MyBatis的Mapper代理方式通过动态代理机制,将接口方法与SQL语句进行映射,使得开发者能够更加方便地进行数据库操作,同时避免了繁琐的SQL映射配置。这种方式使得代码更加清晰简洁,并且提供了良好的可扩展性和可维护性。

相关文章:
MyBatis插件原理探究和自定义插件实现

MyBatis源码剖析之Configuration、SqlSession、Executor、StatementHandler细节

MyBatis源码剖析之二级缓存细节

MyBatis源码剖析之延迟加载源码细节

本文内容到此结束了,
如有收获欢迎点赞👍收藏💖关注✔️,您的鼓励是我最大的动力。
如有错误❌疑问💬欢迎各位指出。
主页共饮一杯无的博客汇总👨‍💻

保持热爱,奔赴下一场山海。🏃🏃🏃

更多推荐

Kubernetes (K8s) 解读:微服务与容器编排的未来

🌷🍁博主猫头虎(🐅🐾)带您GotoNewWorld✨🍁🐅🐾猫头虎建议程序员必备技术栈一览表📖:🛠️全栈技术FullStack:📚MERN/MEAN/MEVNStack|🌐Jamstack|🌍GraphQL|🔁RESTfulAPI|⚡WebSockets|🔄CI/CD|🌐Git&Versio

Kubernetes-01-基础概念篇 基础组件&搭建一个K8S集群

K8S重要技术内容主要涵盖:集群架构、容器化应用部署、ScaleUp/Down、滚动更新、监控检查、集群网络、数据管理、监控与日志一、基础名词1.ClusterCluster是计算、存储、网络资源的集合,利用资源运行各种基于容器的应用2.MasterMaster是Cluster的核心,负责调度、控制。高可用版本,一般至

Kubernetes(K8s)上使用分布式存储(Distributed Storage)

摘要在Kubernetes(K8s)上使用分布式存储(DistributedStorage)是一种常见的方案,它可以为集群中的应用程序提供持久性和可扩展性。以下是在Kubernetes上使用分布式存储的说明:存储类(StorageClass):首先,你需要创建一个Kubernetes的存储类,用于定义分布式存储的属性和

KubeSphere Namespace 数据删除事故分析与解决全记录

作者:宇轩辞白,运维研发工程师,目前专注于云原生、Kubernetes、容器、Linux、运维自动化等领域。前言2023年7月23日在项目上线前夕,K8s生产环境出现故障,经过紧急修复之后,K8s环境恢复正常;另外我们环境引入了KubeSphere云原生平台技术,为了方便研发人员对于K8s权限的细粒度管理,我方手动将K

K8S的CKA考试环境和题目

CKA考试这几年来虽然版本在升级,但题目一直没有大的变化,通过K8S考试的方法就是在模拟环境上反复练习,通过练习熟悉考试环境和考试过程中可能遇到的坑。这里姚远老师详细向大家介绍一下考试的环境和题目,需要详细资料的同学请在文章后面留言。祝大家考试成功。K8S的考试环境CKA考试环境由三台虚拟机组成,这三台虚拟机姚远老师已

3.k8s dashboard设置域名登录案例(ingress版本为1.3.1)

文章目录前言一、安装ingress1.1下载ingress部署文件1.2查看是否安装成功二、配置dashboard域名映射2.1.在windows和linux添加上域名映射2.2生成tls证书2.3新增ingress配置2.3验证总结前言前面搭建了集群,配置了账号密码登录,现在配置k8sdashboard的域名登录,这

Augmented Large Language Models with Parametric Knowledge Guiding

本文是LLM系列文章,针对《AugmentedLargeLanguageModelswithParametricKnowledgeGuiding》的翻译。参数知识引导下的增强大型语言模型摘要1引言2相关工作3LLM的参数化知识引导4实验5结论摘要大型语言模型(LLM)凭借其令人印象深刻的语言理解和生成能力,显著提高了自

GPT4RoI: Instruction Tuning Large Language Model on Region-of-Interest

在图像-文本对上调整大语言模型(LLM)的指令已经实现了前所未有的视觉-语言多模态能力。然而,他们的视觉语言对齐仅建立在图像级别上,缺乏区域级别对齐限制了他​​们在细粒度多模态理解方面的进步。在本文中,我们提出对感兴趣区域进行指令调整。关键设计是将边界框重新表述为空间指令的格式。将空间指令和语言嵌入提取的视觉特征的交错

计算机网络基础知识(非常详细)

1.网络模型1.1OSI七层参考模型七层模型,亦称OSI(OpenSystemInterconnection)参考模型,即开放式系统互联,是网络通信的标准模型。一般称为OSI参考模型或七层模型。它是一个七层的、抽象的模型体,不仅包括一系列抽象的术语或概念,也包括具体的协议。物理层:负责传输原始的比特流,数模转换、模数转

Postman应用——Collection、Folder和Request

文章目录Collection新建CollectionCollection重命名保存Request到Collection在Collection下创建Request删除CollectionFolder新建FolderFolder重命名保存Request到Folder在Folder下创建Request在Folder下创建Fo

MySQL数据库详解 一:安装MySQL数据库及基本管理

文章目录1.数据库的基本概念1.1数据库的组成1.1.1数据1.1.2表1.1.3数据库1.2当前主流数据库及其特点1.3数据库类型1.3.1关系数据库1.3.1.1关系数据库的组成1.3.1.2非关系数据库2.安装MySQL2.1yum安装2.2编译安装MySQL2.2.1前置准备2.2.2编译安装2.2.3修改my

热文推荐