深入MyBatis-运行原理-getMapper获取到接口的代理对象

版权声明:转载需声明本人出品 https://blog.csdn.net/weixin_40288381/article/details/88566168

流程图

在这里插入图片描述

  1. DefaultSqlSessionF调用getMapper方法,其中为configuration下的getMapper方法
  2. configuration下的getMapper方法,其中为mapperRegistry下的getMapper方法
  3. mapperRegistry下的getMapper方法下根据接口类型获取MapperProxyFactory
  4. MapperProxyFactory调用newInstance生成MapperProxy
  5. 创建MapperProxy的代理对象,一路返回到最初调用的DefaultSqlSession

剖析源码

1.DefaultSqlSessionF调用getMapper方法
//传入接口类
sqlSession.getMapper(StudentMapper.class);
2.调用configutaion的getMapper方法
public <T> T getMapper(Class<T> type) {
    return configuration.<T>getMapper(type, this);
  }
3.调用mapperRegistry的getMapper方法
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
  }
  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 {
     //此处将返回MapperProxy的代理对象
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }
4.创建MapperProxy代理对象
 public T newInstance(SqlSession sqlSession) {
 	//生成MapperProxy
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    //生成MapperProxy的代理对象,之后一路返回
    return newInstance(mapperProxy);
  }

小结

DefaultSqlSession下调用getMapper方法,最终根据传入接口的类型生成MapperProxy工厂,创建MapperProxy,最终返回MapperProxy的代理对象。

猜你喜欢

转载自blog.csdn.net/weixin_40288381/article/details/88566168
今日推荐