一 基本查询方法源码解析

1 使用示例

回顾下写法:

  1. @Test
  2. public void test2() throws IOException {
  3. InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
  4. SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
  5. SqlSession sqlSession = factory.openSession();
  6. // 使用JDK动态代理对mapper接口产生代理对象
  7. IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);
  8. //代理对象调用接口中的任意方法,执行的都是动态代理中的invoke方法
  9. List<User> all = mapper.findAll();
  10. for (User user : all) {
  11. System.out.println(user);
  12. }
  13. }

思考一个问题,通常的Mapper接口我们都没有实现的方法却可以使用,是为什么呢?答案很简单:动态代理

开始之前介绍一下MyBatis初始化时对接口的处理:MapperRegistry是Configuration中的一个属性,
它内部维护一个HashMap用于存放mapper接口的工厂类,每个接口对应一个工厂类。mappers中可以配置接口的包路径,或者某个具体的接口类。

<mappers>
  <mapper class="com.lagou.mapper.UserMapper"/>
  <package name="com.lagou.mapper"/>
</mappers>

当解析mappers标签时,它会判断解析到的是mapper配置文件时,会再将对应配置文件中的增删改查标签 封装成MappedStatement对象,存入mappedStatements中。(传统方式的基本查询介绍了)

当判断解析到接口时,会建此接口对应的MapperProxyFactory对象,存入HashMap中,key = 接口的字节码对象,value =此接口对应的MapperProxyFactory对象。

2 Mapper接口的扫描

2.1 包的扫描

org.apache.ibatis.builder.xml.XMLConfigBuilder#parseConfiguration

    private void parseConfiguration(XNode root) {
        try {
            // 省略部分代码
            // 解析 <mappers /> 标签
            mapperElement(root.evalNode("mappers"));
        } catch (Exception e) {
            throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
        }
    }

撒大大说

private void mapperElement(XNode parent) throws Exception {
        if (parent != null) {
            // 遍历子节点
            for (XNode child : parent.getChildren()) {
                // 如果是 package 标签,则扫描该包
                if ("package".equals(child.getName())) {
                    // 获取 <package> 节点中的 name 属性
                    String mapperPackage = child.getStringAttribute("name");
                    // 从指定包中查找 mapper 接口,并根据 mapper 接口解析映射配置
                    configuration.addMappers(mapperPackage);
                // 如果是 mapper 标签,

               }
        }
    }

Configuration#addMappers


/**
* org.apache.ibatis.session.Configuration#addMappers(java.lang.String)
*/
public void addMappers(String packageName) {
    // 扫描该包下所有的 Mapper 接口,并添加到 mapperRegistry 中
    mapperRegistry.addMappers(packageName);
}

/**
 * org.apache.ibatis.binding.MapperRegistry#addMappers(java.lang.String)
 */
public void addMappers(String packageName) {
    addMappers(packageName, Object.class);
}

/**
 * 扫描指定包,并将符合的类,添加到 {@link #knownMappers} 中
 *
 * @since 3.2.2
 */
public void addMappers(String packageName, Class<?> superType) {
    // 扫描指定包下的指定类
    ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<>();
    resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
    Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
    // 遍历,添加到 knownMappers 中
    for (Class<?> mapperClass : mapperSet) {
        addMapper(mapperClass);
    }
}

3 sqlSession#getmapper()


进入 sqlSession.getMapper(UserMapper.class )中

//DefaultSqlSession 中 的 getMapper 
public T getMapper(Class type) {
    return configuration.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) {
    // 获得 MapperProxyFactory 对象
    final MapperProxyFactory<T> mapperProxyFactory = 
        (MapperProxyFactory<T>) knownMappers.get(type);
    // 不存在,则抛出 BindingException 异常
    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动态代理的invocationHandler接口的实现类mapperProxy
    final MapperProxy<T> mapperProxy = 
        new MapperProxy<>(sqlSession, mapperInterface, methodCache);
    // 调用了重载方法
    return newInstance(mapperProxy);
}

//MapperProxy 类,实现了 InvocationHandler 接口
public class MapperProxy<T> implements InvocationHandler, Serializable {
    //省略部分源码
    private final SqlSession sqlSession; 
    private final Class mapperInterface;
    private final Map<Method, MapperMethod> methodCache;
    //构造,传入了 SqlSession,说明每个session中的代理对象的不同的!
    public MapperProxy(SqlSession sqlSession, Class mapperInterface, 
                       Map<Method, MapperMethod> methodCache) {
        this.sqlSession = sqlSession; 
        this.mapperInterface = mapperInterface; 
        this.methodCache = methodCache;
    }
    //省略部分源码
}

4 MapperProxy#invoke

在动态代理返回了示例后,我们就可以直接调用mapper类中的方法了,但代理对象调用方法,执行是在MapperProxy中的invoke方法中:org.apache.ibatis.binding.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);
}

4 mapperMethod#execute

进入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);
            // 转换 rowCount
            result = rowCountResult(sqlSession.update(command.getName(), param));
            break;
        }
        case DELETE: {
            // 转换参数
            Object param = method.convertArgsToSqlCommandParam(args);
            // 转换 rowCount
            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);
                // 执行查询,返回 Map
            } else if (method.returnsMap()) {
                result = executeForMap(sqlSession, args);
                // 执行查询,返回 Cursor
            } else if (method.returnsCursor()) {
                result = executeForCursor(sqlSession, args);
                // 执行查询,返回单个对象
            } else {
                // 转换参数
                Object param = method.convertArgsToSqlCommandParam(args);
                // 查询单条
                result = sqlSession.selectOne(command.getName(), param);
                if (method.returnsOptional() &&
                    (result == null || !method.getReturnType().equals(result.getClass()))) {
                    result = Optional.ofNullable(result);
                }
            }
            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;
}

本质仍然是由sqlSession中的方法进行执行