注
以下内容都是根据尚硅谷2018年mybatis源码解析做的课程笔记,视频链接: https://www.bilibili.com/video/BV1mW411M737?p=74&share_source=copy_web 另外特别感谢雷丰阳老师的讲解
拿到sqlSession,接下来就该getMapper了
SqlSession sqlSession=MybatisUtils.getSqlSession();
TypeDao dao=sqlSession.getMapper(TypeDao.class);
一路往下
<T> T getMapper(Class<T> var1);
public <T> T getMapper(Class<T> type) {
return this.configuration.getMapper(type, this);
}
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return this.mapperRegistry.getMapper(type, sqlSession);
}
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory)this.knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
} else {
try {
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception var5) {
throw new BindingException("Error getting mapper instance. Cause: " + var5, var5);
}
}
}
最终在this.mapperRegistry.getMapper方法真正实现了mapper 其中
return mapperProxyFactory.newInstance(sqlSession);
它new了一个Instance
public T newInstance(SqlSession sqlSession) {
MapperProxy<T> mapperProxy = new MapperProxy(sqlSession, this.mapperInterface, this.methodCache);
return this.newInstance(mapperProxy);
}
这里面又new了一个mapper的代理对象
而这个类又实现了动态代理 最后他调用本类的newInstance,这里面又调用了java本类的代理对象
protected T newInstance(MapperProxy<T> mapperProxy) {
return Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);
}
所以我们最终拿到的mapper是mapperProxy的代理对象 返回的mapper又包含了sqlSession,最终才能用于增删改查
|