回顾下写法:
public static void main(String[] args) {
//前三步都相同
InputStream inputStream =
Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory factory = new
SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = factory.openSession();
//这里不再调用sqlSession,而是获得了接口对象,调用接口中的方法。
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> list = mapper.getUserByName("tom");
}
思考一个问题,通常的Mapper接口我们都没有实现方法却可以直接使用,是为什么?答案很简单,动态代理。
开始之前介绍一下Mybatis初始化时对接口的处理:MapperRegistry是Configuration的一个属性,它内部维护了一个HashMap用于存放mapper接口的工厂类,每一个接口对应一个工厂类。mappers中可以配置接口的包接口,或者某个具体的接口类。
<mappers>
<mapper class="com.lagou.mapper.UserMapper"/>
<package name="com.lagou.mapper"/>
</mappers>
当解析mappers标签时,它会判断解析到的是mapper配置文件时,会再对应配置文件中的增删查改标签一一封装成MappedStatement对象,存入mappedStatement。当判断解析到接口时,会建此接口对应的MapperProxyFactory对象,存入HashMap中,key=接口的字节码对象,value=此接口对应的MapperProxyFactory对象。
源码剖析-getMapper
DefaultSqlSession#getMapper
//DefaultSqlSession#getMapper
public <T> T getMapper(Class<T> type) {
return configuration.<T>getMapper(type, this);
}
//Configuration#getMapper
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
//MapperRegistry#getMapper
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
//从MapperRegistry中的HashMap中拿MapperProxyFactory
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#newInstance
public T newInstance(SqlSession sqlSession) {
// 创建JDK动态代理的Handler类
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
//调用重载方法
return newInstance(mapperProxy);
}
MapperProxy类,实现了InvocationHandler接口
public class MapperProxy<T> implements InvocationHandler, Serializable {
//省略部分源码
private final SqlSession sqlSession;
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache;
}
//构造方法,传入了SqlSessio,说明每个session中的代理对象
public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
this.sqlSession = sqlSession;
this.mapperInterface = mapperInterface;
this.methodCache = methodCache;
}
//省略部分源码
}
源码剖析-invoke
在动态代理返回了示例后,我们就可以调用mapper类中的方法了,但代理对象调用方法,执行是MapperProxy中的invoke方法中。
MapperProxy#invoke
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)) {
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
// 获取 MapperMethod 对象
final MapperMethod mapperMethod = cachedMapperMethod(method);
//重点在这,MapperMethod最终调用了执行方法
return mapperMethod.execute(sqlSession, args);
}
进入execute方法
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
//判断mapper中的方法类型,最终调用的还是SqlSession中的方法
switch (command.getType()) {
case INSERT: {
//转换参数
Object param = method.convertArgsToSqlCommandParam(args);
//执行 INSERT 操作 ,转换 rowCount
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:
//无返回,并且有 ResultHandler 方法参数,则将查询结果提交给ResultHandler 进行处理
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());
}
//返回结果为null,并且返回类型为基本类型,则抛出 BindingException异常
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;
}