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

经过前两篇文章的分析,我们知道了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配置的匹配。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Survivor001

你可以相信我,如果你愿意的话

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值