MyBatis源码分析之——面试官问我如何获得Mapper对象?我是这样说的!

咱们直入主题,分析源码吧!从获取Mapper开始吧。


UserMapper userMapper = sqlSession.getMapper(UserMapper.class);



public <T> T getMapper(Class<T> type) {
    return configuration.getMapper(type, this);
}


mapperRegistry.getMapper是从MapperRegistry的knownMappers里面取的,knownMappers里面存的是接口类型(interface mapper.UserMapper)和工厂类(MapperProxyFactory)。




public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
}


从knownMappers的Map里根据接口类型(interface mapper.UserMapper)取出对应的工厂类



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<>(sqlSession, mapperInterface, methodCache);
  return newInstance(mapperProxy);
}


这里通过JDK动态代理返回代理对象MapperProxy。


protected T newInstance(MapperProxy<T> mapperProxy) {
  //mapperInterface是interface mapper.UserMapper
  return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
上一篇:MyBatis源码分析之——SqlSession会话创建过程


下一篇:js的动态加载、缓存、更新以及复用(四)