经过前两篇文章的分析,我们知道了mybatis对配置文件mybatis-config.xml和mapper.xml 的一个加载原理,以及配置信息Configuraction和执行器Excutor 信息封装入DefaultSqlSession中。
现在针对mapper相关源码进行解析,分析Mybaits是如果没有实体类的情况下,可以执行接口方法?
示例:
进入getmapper方法,实现类DefaultSqlSession:
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<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
MapperProxy类,该类实现了InvocationHandler接口,实现了invoke方法。
回过头进入newInstance方法:
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
这就很清楚了创建了一个jdk代理对象。
总结 : getmapper方法创建了mapper接口的JDK代理对接,并返回。因为mapper接口核心目的是提供sql方法的全限定名,使用其找到对应的存储在mappedstatements中的xml配置sql内容,执行sql,所以这就是为什么不需要实现类就可以进行方法调用的根本原因:通过代理实现调用invoke方法实现mappedstatement配置的匹配。