- 调用getMapper方法
SqlSession#getMapper
->(DefaultSqlSession)configuration#getMapper
-->(Configuration)mapperRegistry#getMapper
//MapperRegistry类
@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);
}
}
//MapperProxyFactroy类
@SuppressWarnings("unchecked")
//这里即产生一个mapper接口的代理对象 代理对象的调用在下面类中体现
protected T newInstance(MapperProxy<T> mapperProxy) {
//参数分别为Mapper接口的类加载器、mapper接口、对应的invocationHandler
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
//MapperRegistry调用的是这个方法 这个方法又调用上面产生代理对象的方法
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
//MapperProxy代理类中invoke方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
//如果该方法是Object中的基本方法 则调用这个循环代码
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else if (isDefaultMethod(method)) {
//如果接口方法是被Default修饰符修饰 则调用这个循环代码
//default关键字是JDK1.8中接口中使用 被该关键字修饰的方法 相当于默认的方法
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
//否则该方法即是Mapper中声明的方法 即调用SqlSession来执行
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}
由此可见,getMapper的过程其实也是动态代理实现的过程。至此Sqlsession#getMapper
过程介绍完毕。
网友评论