mybatis随笔三之SqlSession

在上一篇文章我们已经得到了DefaultSqlSession,接下来我们对sqlSession.getMapper(DemoMapper.class)这种语句进行分析
@Override
  public <T> T getMapper(Class<T> type) {
    return configuration.<T>getMapper(type, this);
  }
在这里又调用了如下方法
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
  }
getMapper方法代码如下
@SuppressWarnings("unchecked")
  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);
    }
  }
在SqlSessionFactoryBuilder创建SqlSessionFactory的过程中已经将mapper接口到了knownMappers中,找不到的话这里会抛错。
public T newInstance(SqlSession sqlSession) {
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }
首先实例化一个MapperProxy对象,我们对Mapper接口的调用实际上使用的MapperProxy对象,mapperInterface在build factory的过程中已经设置过值了,methodCache后面会提,暂时不提。
protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }
从这里可以得知我们返回的mapper对象实际是个代理对象。

由debug可清晰的看到返回的mapper对象是由jdk代理生成。

至此SqlSession的getMapper方法分析结束。


posted on 2017-02-14 10:34  颓废的悠然  阅读(1016)  评论(0编辑  收藏  举报

导航