MyBatis提供了接口映射的功能,能够使我们以面向对象的方式调用XML或者接口注解配置的SQL语句。诸如AccountMapper这些映射接口并没有实现类:
public interface AccountMapper{
int login(Map<String,Object> map);
}
那么接口映射的原理是什么呢?
首先,映射接口并没有实现类,是通过JDK动态代理生成的代理对象。MyBatis可以在mybatis-config.xml文件中配置映射接口所在的包:
<mappers>
<package name="qy.ssh.mapper"/>
</mappers>
解析的时候,就可以将包下的所有映射接口解析成代理工厂对象(MapperProxyFactory):
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
knownMappers.put(type, new MapperProxyFactory<T>(type));
其次,看映射接口生成过程:
// DefaultSqlSession:默认会话实现类
@Override
public <T> T getMapper(Class<T> type) {
return configuration.<T>getMapper(type, this);
}
// Configuration:MyBatis核心类
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
// 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);
}
}
// MapperProxyFactory:代理工厂
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
// 调用JDK动态代理类Proxy生成代理对象
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
聚焦到最后一个方法,这个方法就是通过Proxy代理类动态生成映射接口对象的:
Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy)
重点就在传入的第三个参数MapperProxy,这个参数需要实现InvocationHandler接口,重写invoke方法,生成的代理对象调用对象的方法,我们看生成的class文件就可以知道,实质上调用的就是invoke方法。代理模式能够实现在不改变被代理对象的基础上,增加新的功能就是在invoke方法里面添加的代码(诸如Spring AOP功能)。
最后,也就是核心的,映射接口的代理对象具体是怎么执行方法的?通过上面的分析可知,实际上调用的是MapperProxy的invoke方法:
// MapperProxy 实现了InvocationHandler接口
// 重写了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);
}
看invoke方法的最后一行可知,实际上调用的是MapperMethod的execute方法:
// MapperMethod
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
switch (command.getType()) {
case INSERT: {
Object param = method.convertArgsToSqlCommandParam(args);
// 调用sqlSession的insert方法
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;
}
case UPDATE: {
Object param = method.convertArgsToSqlCommandParam(args);
// 调用sqlSession的update方法
result = rowCountResult(sqlSession.update(command.getName(), param));
break;
}
case DELETE: {
Object param = method.convertArgsToSqlCommandParam(args);
// 调用sqlSession的delete方法
result = rowCountResult(sqlSession.delete(command.getName(), param));
break;
}
case SELECT:
// 调用sqlSession的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;
}
上述的代码告知我们MapperMethod的execute方法最终执行的是DefaultSqlSession的CRUD方法,而CRUD方法均需要传入statement参数(全限定名的SQL语句的ID),statement存储在Configuration的mappedStatements 里:
protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection");
mappedStatements是在初始化MyBatis核心类Configuration的时候解析mapper文件生成的,具体初始化过程,后面的博文中会有。
通过以上分析的可知,映射接口通过代理模式生成代理对象,访问代理对象的方法实质上访问的仍是解析mapper文件生成的配置好的SQL语句。