第五篇文章中,我们获取到了SqlSession对象,然后我们在执行的时候是通过获取Mapper,然后通过执行mapper的方法来获取我们需要的数据,这篇我们就看一下这个通过SqlSession获取Mapper的过程。
DefaultSqlSession
public <T> T getMapper(Class<T> type) {
//这里调用的是configuration的getMapper方法
return configuration.<T>getMapper(type, this);
}
configuration
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
//这里其实调用得失mapperRegistry的getMapper方法
return mapperRegistry.getMapper(type, sqlSession);
}
mapperRegistry
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
//首先我们在缓存中拿到当前class对应的MapperProxyFactory
//MapperProxyFactory是在我们最开始解析Mapper的时候存入的
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
//这里必须是解析过的Mapper才能执行
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
//这里获取mapper对象,主要是通过mapperProxyFactory对象,传入我们的sqlSession对象
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
mapperProxyFactory
public T newInstance(SqlSession sqlSession) {
//生成MapperProxy对象
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
protected T newInstance(MapperProxy<T> mapperProxy) {
//这里其实是生成了一个当前mapper的代理对象
//后续执行调用的时候其实是交给mapperProxy的
//mapperProxy实现了InvocationHandler
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
这里我们就获取到了当前mapper的一个代理对象,这里交给MapperProxy去处理,我们在下一篇详细看一下这个执行的方法。