Mybatis:Mapper接口编程原理分析(三)

在上一篇文章Mybatis:Mapper接口编程原理分析(二)中,已经知道 mapper 接口是怎么注册的了,那么现在就是需要获取 mapper 接口的代理了。
在使用 Mybatis 时,我们都是通过如下代码去获取 mapper 接口的代理的:

sqlSession.getMapper(UserMapper.class)

代码只有一行,就获取了 mapper 接口的代理对象了,那么在内部是怎么一回事呢?

  • DefaultSqlSession
public <T> T getMapper(Class<T> type) {
        // 从 Configuration 获取 mapper 接口代理
        return this.configuration.getMapper(type, this);
}
  • Configuration
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
         // 从 MapperRegistry 获取 mapper 接口代理
        return this.mapperRegistry.getMapper(type, sqlSession);
}
  • MapperRegistry
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        // 获取 mapper 接口的代理工厂
        MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory)this.knownMappers.get(type);
        if (mapperProxyFactory == null) {
            throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
        } else {
            try {
                // 生成 mapper 代理
                return mapperProxyFactory.newInstance(sqlSession);
            } catch (Exception var5) {
                throw new BindingException("Error getting mapper instance. Cause: " + var5, var5);
            }
        }
}
  • MapperProxyFactory
public T newInstance(SqlSession sqlSession) {
        // MapperProxy 实现了 InvocationHandler
        MapperProxy<T> mapperProxy = new MapperProxy(sqlSession, this.mapperInterface, this.methodCache);
        // 获取 mapper 代理
        return this.newInstance(mapperProxy);
 }
// 生成 mapper 代理对象
protected T newInstance(MapperProxy<T> mapperProxy) {
        return Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);
}

序列图如下:


获取 mapper 代理
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1 引言# 本文主要讲解JDBC怎么演变到Mybatis的渐变过程,重点讲解了为什么要将JDBC封装成Mybait...
    七寸知架构阅读 76,646评论 36 979
  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,708评论 0 4
  • 红楼梦随便一件衣服拿到淘宝上去卖,关键词够长还很少带重样:大红羽纱面白狐狸皮鹤氅、缕金百蝶穿花大红洋缎窄褙袄、石青...
    你也要吃一个吗阅读 293评论 0 0
  • 那是人们从未经过的天空 我在天空中流浪、沉醉、迷失 我在天空中一无所有 我在天空中 干净的天空中迷醉 白色的云 蓝...
    贪图的贪阅读 86评论 0 0
  • 婚姻并不只是两个个人的事,其实是两家人的事,更是孩子们的事。 1 这几天宝强宣告离婚,老婆出轨经纪人的事件上了头条...
    妍之有礼阅读 365评论 0 0