学无先后,达者为师

网站首页 编程语言 正文

Mybatis3 深入源码 -- getMapper返回代理mapper源码分析

作者:Survivor001 更新时间: 2022-02-15 编程语言

经过前两篇文章的分析,我们知道了mybatis对配置文件mybatis-config.xml和mapper.xml 的一个加载原理,以及配置信息Configuraction和执行器Excutor 信息封装入DefaultSqlSession中。

现在针对mapper相关源码进行解析,分析Mybaits是如果没有实体类的情况下,可以执行接口方法?

示例:

 进入getmapper方法,实现类DefaultSqlSession:

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    if (mapperProxyFactory == null) {
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
      // 初始化
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }

 继续:

 public T newInstance(SqlSession sqlSession) {
  
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

MapperProxy类,该类实现了InvocationHandler接口,实现了invoke方法。

 回过头进入newInstance方法:

  protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

这就很清楚了创建了一个jdk代理对象。

 

总结 : getmapper方法创建了mapper接口的JDK代理对接,并返回。因为mapper接口核心目的是提供sql方法的全限定名,使用其找到对应的存储在mappedstatements中的xml配置sql内容,执行sql,所以这就是为什么不需要实现类就可以进行方法调用的根本原因:通过代理实现调用invoke方法实现mappedstatement配置的匹配。

原文链接:https://blog.csdn.net/qq_31142237/article/details/120410946

栏目分类
最近更新