getMapper()时序图
1.调用getMapper方法
DeptMapper mapper = sqlSession.getMapper(DeptMapper.class);
2.进入方法内部
@Override
public <T> T getMapper(Class<T> type) {
//最后会去调用MapperRegistry.getMapper
return configuration.<T>getMapper(type, this);
}
3.将mapper的class和defaultSqlSession转入configuration类的getMapper()方法
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
4.调用mapperRegistry的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);
}
}
其中MapperRegistry在解析mapper.xml文件的时候已经将namespace放入knownMappers中
/**
* 映射器注册机
*
*/
public class MapperRegistry {
private Configuration config;
//将已经添加的映射都放入HashMap
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
5.调用 mapperProxyFactory.newInstance(sqlSession)
public T newInstance(SqlSession sqlSession) {
// 创建mapperProxy
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
6.创建jdk动态代理对象,里边封装有SqlSession信息
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
//用JDK自带的动态代理生成映射器,创建代理对象
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}