SqlSession
从SqlSession下手,因为SqlSession是一个接口,我们就从他其中一个子类来从大体上了解Mybatis是怎么代理接口的,主要来看DefaultSqlSession这个子类
DefaultSqlSession
@Override
public <T> T getMapper(Class<T> type) {
return configuration.<T>getMapper(type, this);
}
我们点进去getMapper方法,一直往下,最后来到这个方法,在这里,knownMappers是已经存有每个接口对应的MapperProxyFactory对象的map,这是之前就存好的
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);
}
}
而这个方法最主要的是newInstance(sqlSession)这个方法,我们的Mapper代理对象就是从这个方法生成,我们再来分析一下这个方法
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
再往下,就是使用jdk动态代理来生成代理类了,而此时最主要的还是这句代码
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
MapperProxy
点进去,我们发现MapperProxy实现了InvocationHandler这个接口,所以,mapperProxy就是一个调用处理器对象,我们去看其invoke方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else if (isDefaultMethod(method)) {
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}
看到最后,这里有一个cachedMapperMethod,其实这里就是缓存起来的Mapper对象,有就直接拿,没有就重新创建。而最后的mapperMethod.execute(sqlSession, args)就是真正执行sql的方法。
我们可以发现通过switch,case,其最终也是调用sqlSession的方法