从 Mybatis 之 构造Mapper (MapperProxy) http://blog.csdn.net/zsg88/article/details/77921009 一文中我们已经知道
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
返回的其实是一个MapperProxy代理类
org.apache.ibatis.binding.MapperProxyFactory
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
那么又是怎样通过Mapper代理类调用具体方法的。我们先看MapperProxy类实现的InvocationHanlder.invoke方法:
org.apache.ibatis.binding.MapperProxy
@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);
}
判断是否是一个类,如果是一个类,那么久直接传递方法和参数调用即可。但我们知道此时是一个接口(也可以自己实现接口,旧版本通常这样做)。如果不是一个类的话,就会创建一个MapperMethod对象来执行方法。
MapperMethod类和数据库进行操作,看看execute方法:
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
switch (command.getType()) {
case INSERT: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;
}
case UPDATE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
break;
}
case DELETE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
break;
}
case SELECT:
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
} else if (method.returnsMany()) {
result = executeForMany(sqlSession, args);
} else if (method.returnsMap()) {
result = executeForMap(sqlSession, args);
} else if (method.returnsCursor()) {
result = executeForCursor(sqlSession, args);
} else {
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param);
}
break;
case FLUSH:
result = sqlSession.flushStatements();
break;
default:
throw new BindingException("Unknown execution method for: " + command.getName());
}
if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
throw new BindingException("Mapper method '" + command.getName()
+ " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
}
return result;
}
我们选择常见的"SELECT"sql语句来进行解读,其中的executeForMany方法:
private <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
List<E> result;
Object param = method.convertArgsToSqlCommandParam(args);
if (method.hasRowBounds()) {
RowBounds rowBounds = method.extractRowBounds(args);
result = sqlSession.<E>selectList(command.getName(), param, rowBounds);
} else {
result = sqlSession.<E>selectList(command.getName(), param);
}
// issue #510 Collections & arrays support
if (!method.getReturnType().isAssignableFrom(result.getClass())) {
if (method.getReturnType().isArray()) {
return convertToArray(result);
} else {
return convertToDeclaredCollection(sqlSession.getConfiguration(), result);
}
}
return result;
}
真正执行sql语句的地方
if (method.hasRowBounds()) {
RowBounds rowBounds = method.extractRowBounds(args);
result = sqlSession.<E>selectList(command.getName(), param, rowBounds);
} else {
result = sqlSession.<E>selectList(command.getName(), param);
}
最后又回到了sqlSession的方法中。看到传递了什么参数进来,跟踪command.getName()是怎么来的。
private final SqlCommand command;
我们可以发现这个SqlCommand是MapperMethod的静态内部类。
//org.apache.ibatis.binding.MapperMethod public static class SqlCommand { private final String name; private final SqlCommandType type; public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
String statementName = mapperInterface.getName() + "." + method.getName();//获取接口+方法名
MappedStatement ms = null; if (configuration.hasStatement(statementName)) {//定义一个MappedStatement
ms = configuration.getMappedStatement(statementName);//从Configuration对象查找是否有这个方法的全限定名称 //有,则根据方法的全限定名称获取MappedStatement实例
String parentStatementName = method.getDeclaringClass().getName() + "." + method.getName(); if (configuration.hasStatement(parentStatementName)) { //在向上的父类查找是否有这个全限定方法名 ms = configuration.getMappedStatement(parentStatementName); //有,则根据方法的全限定名称获取MappedStatement实例 } } if (ms == null) { if(method.getAnnotation(Flush.class) != null){ name = null; type = SqlCommandType.FLUSH; } else { throw new BindingException("Invalid bound statement (not found): " + statementName); } } else { name = ms.getId(); //这个ms.getId,其实就是我们在mapper.xml配置文件中配置一条sql语句时开头的<select id="xxx" ...,即是接口的该方法名全限定名称 type = ms.getSqlCommandType(); //显然这是将sql是何种类型(insert、update、delete、select)赋给type if (type == SqlCommandType.UNKNOWN) { throw new BindingException("Unknown execution method for: " + name); } } } public String getName() { return name; } public SqlCommandType getType() { return type; } }} else if (!mapperInterface.equals(method.getDeclaringClass())) { // issue #35 //如果没有在Configuration对象中找到这个方法,则向上父类中获取全限定方法名