mybatis核心组件之MapperMethod
注释: 跟踪
mapper
执行接口方法到数据库执行
sql
语句的源码过程
// mybatis-spring
UserMapper mapper = context.getBean(UserMapper.class);
System.out.println(mapper.selectAny());
可以看到mapper
是MapperProxy产生的代理类,那么MapperProxy中可定有invok
方法对目标方法进行了增强处理
MapperProxy
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 如果方法是Object类的方法,则直接反射执行
if (Object.class.equals(method.getDeclaringClass())) {
try {
return method.invoke(this, args);
} catch (Throwable var5) {
throw ExceptionUtil.unwrapThrowable(var5);
}
} else {
// 获取MapperMethod
MapperMethod mapperMethod = this.cachedMapperMethod(method);
// 执行sql语句
return mapperMethod.execute(this.sqlSession, args);
}
}
- 先判断执行的方法是不是Object类的方法,比如
tostring
,hashcode
等方法,是的话则直接反射执行这些方法 - 如果不是,从缓存中获取MapperMethod,如果为空则创建并加入缓存,然后执行
sql
语句
private MapperMethod cachedMapperMethod(Method method) {
// 根据方法从缓存中获取
MapperMethod mapperMethod = (MapperMethod)this.methodCache.get(method);
if (mapperMethod == null) {
// 不存在则创建一个
mapperMethod = new MapperMethod(this.mapperInterface, method, this.sqlSession.getConfiguration());
// 放入缓存
this.methodCache.put(method, mapperMethod);
}
return mapperMethod;
}
MapperMethod
构造函数
private final MapperMethod.SqlCommand command;
private final MapperMethod.MethodSignature method;
public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
this.command = new MapperMethod.SqlCommand(config, mapperInterface, method);
this.method = n