MyBatis源码解析(五):执行Mapper,获取初始结果集

        前言:MyBatis源码解析(四):初始化Mapper中,通过 MapperProxyFactory 已经成功获取到执行 Mapper 的代理对象,这一篇将使用该代理对象执行 Statement,获取到SQL执行的初始结果。另外,本篇步涉及ORM映射

一,执行流程

MyBatis源码解析(五):执行Mapper,获取初始结果集

二,执行步骤

    1,初始化 Mapper 代理对象回顾

        * MapperProxyFactory:通过java动态动态获取代理对象

// Mapper.Statement执行缓存
private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();

protected T newInstance(MapperProxy<T> mapperProxy) {
    // 通过JDK动态代理方式, 生成Mapper的代理对象,
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

  public T newInstance(SqlSession sqlSession) {
    // 初始化MapperProxy, 该类为InvocationHandler实现类, 动态代理最终执行该类的Invoke方法
    // mapperInterface 在初始化传递过程中已经初始化为当前Mapper类型
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

    2,通过 Mapper 代理对象触发 Statement 执行

        * Statement 触发语句

UserVO userVO = mapper.selectUserById(1);

        * MapperProxy :Statement 最终执行语句,因为通过动态代理触发,此时会执行 InvocationHandler 的 invoke()方法

// MapperProxyFactory实例化时候, 指定InvocationHandler为MapperProxy
  // 则通过Mapper代理对象进行Statement执行时, 执行该invoke()方法
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      // 如果方法是Object类方法, 直接执行
      // 例如equals, hashCode等方法
      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);
    }
    // 有效Statement, 根据method生成mapperMethod进行执行
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }

    3,根据 Method 生成有效的 MapperMethod,并区分执行类型

        * MapperProxy:根据有效 Statement 的 Method 对象,生成 MapperMethod 对象

private MapperMethod cachedMapperMethod(Method method) {
    // 从Statement缓存容器中获取当前Statement, 拿到直接返回
    MapperMethod mapperMethod = methodCache.get(method);
    if (mapperMethod == null) {
      // 从缓存集合中未获取到Statment, 初始化当前Statement为MapperMethod
      // 并添加初始化后的MapperMethod到缓存集合
      // mapperInterface, sqlSession, methodCache在构造Mapper代理对象时已经通过MapperProxy初始化传递
      // MapperMethod初始化会从Configuration配置中初始化SqlCommand, MethodSignature信息
      // 表示当前Statment的SQL类型和状态等信息
      mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
      // 添加当前Mapper.Statement到缓存中
      methodCache.put(method, mapperMethod);
    }
    return mapperMethod;
  }

        * MapperMethod:构造器中,会生成 SqlCommand 和 MethodSignature 两个对象,表示SQL和Statement基本信息

public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
    this.command = new SqlCommand(config, mapperInterface, method);
    this.method = new MethodSignature(config, mapperInterface, method);
  }

        * MapperMethod:execute(),区分执行类型,并调用 SqlSession 进行具体操作

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);
          // 调用SqlSession单条数据查询执行方法
          // SqlSession在初始化SqlSession分析中已经指明, 此处应为DefaultSqlSession
          // 单数据查询, 且查询结果为 VO
          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;
  }

    4,调用 SqlSession 操作方法,进行数据操作

        * DefaultSqlSession:因为执行 Statement 为单条数据查询,调用 selectOne() 方法

public <T> T selectOne(String statement, Object parameter) {
    // Popular vote was to return null on 0 results and throw exception on too many.
    // 单条查询调用多条查询的接口, 对返回数据解析, 获取有效数据
    List<T> list = this.<T>selectList(statement, parameter);
    if (list.size() == 1) {
      return list.get(0);
    } else if (list.size() > 1) {
      throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
    } else {
      return null;
    }
  }

        * 在 selectOne() 中,调用 selectList() 方法,实现接口复用

public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
      // 从Configuration对象中根据Statment名称获取有效的MappedStatement
      MappedStatement ms = configuration.getMappedStatement(statement);
      // 调用Executor执行查询
      // Executor初始化阶段已经被包装 CachingExecutor(SimleExecutor)
      return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

        * 从 Configuration 中获取有效的 Statement

public MappedStatement getMappedStatement(String id, boolean validateIncompleteStatements) {
    if (validateIncompleteStatements) {
      buildAllStatements();
    }
    return mappedStatements.get(id);
  }

    5,调用执行器 Executor 执行查询语句

        * CachingExecutor:执行第一层 query() 方法

public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
    // 获取Statment执行的BoundSql, 包含Sql, 参数, 返回结果等信息
    BoundSql boundSql = ms.getBoundSql(parameterObject);
    // 创建数据缓存
    CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
    // 继续进行数据查询
    return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

        * CachingExecutor:执行第二层 query() 方法

public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
      throws SQLException {
    // 先从缓存中获取一次数据, 缓存中存在数据, 直接返回缓存中的数据
    Cache cache = ms.getCache();
    if (cache != null) {
      flushCacheIfRequired(ms);
      if (ms.isUseCache() && resultHandler == null) {
        ensureNoOutParams(ms, boundSql);
        @SuppressWarnings("unchecked")
        List<E> list = (List<E>) tcm.getObject(cache, key);
        if (list == null) {
          list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
          tcm.putObject(cache, key, list); // issue #578 and #116
        }
        return list;
      }
    }
    // 缓存中没有数据, 装饰者模式, 经过BaseExecutor转发到SimpleExecutor继续进行数据查询
    return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

        * BaseExecutor:装饰者模式,转发到 BaseExecutor 继续执行 query() 方法

public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
    if (queryStack == 0 && ms.isFlushCacheRequired()) {
      // 清空数据缓存
      clearLocalCache();
    }
    List<E> list;
    try {
      queryStack++;
      // 先从缓存中获取数据
      list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
      if (list != null) {
        // 缓存中数据不为空, 参数处理后直接返回缓存数据
        handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
      } else {
        // 缓存数据为空, 从数据库查询
        list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
      }
    } finally {
      queryStack--;
    }
    // 延迟加载策略
    if (queryStack == 0) {
      for (DeferredLoad deferredLoad : deferredLoads) {
        deferredLoad.load();
      }
      // issue #601
      deferredLoads.clear();
      if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
        // issue #482
        clearLocalCache();
      }
    }
    return list;
  }

        * BaseExecutor:缓存未加载到,从数据库中获取有效数据

private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    List<E> list;
    // 添加特殊表示, 标识当前Statemnt存在语句正在执行
    localCache.putObject(key, EXECUTION_PLACEHOLDER);
    try {
      // doQuery方法由子类实现, 当前子类SimpleExecutor
      list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
    } finally {
      // 执行完成后移除该标识
      localCache.removeObject(key);
    }
    // 并添加查询到的数据结果添加到缓存中
    localCache.putObject(key, list);
    if (ms.getStatementType() == StatementType.CALLABLE) {
      localOutputParameterCache.putObject(key, parameter);
    }
    return list;
  }

    6,SimpleExecutor 执行 doQuery() 方法解析

        * SimpleExecutor:doQuery()方法

public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    Statement stmt = null;
    try {
      // 获取配置信息
      Configuration configuration = ms.getConfiguration();
      // 获取StatementHandler, 生成已经被Plugin代理的执行器
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
      // 获取数据库连接, 并注册相关事务
      // 此处使用JDBC连接连接, 会调用JDBCConnection进行数据库连接处理
      stmt = prepareStatement(handler, ms.getStatementLog());
      // 数据执行
      return handler.<E>query(stmt, resultHandler);
    } finally {
      closeStatement(stmt);
    }
  }

    7,初始化 StatementHandler 处理器

        * 第一:初始化外层 RoutingStatementHandler 处理器

public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    // 首先初始化StatementHandler为RoutingStatementHandler
    StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
    // 循环插件生成StatementHandler的代理对象, 此处代理为循环代理
    statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
    return statementHandler;
  }

        * 第二:RoutingStatementHandler 内部,根据 MappedStatement.statementType 属性,初始化具体处理器;到这一步后,确保所有的 StatementHandler 能够持有数据查询和组装过程中的所有引用

public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {

    // 根据getStatementType()进行内部初始化, 此次初始化为PreparedStatementHandler
    switch (ms.getStatementType()) {
      case STATEMENT:
        delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case PREPARED:
        delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case CALLABLE:
        delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      default:
        throw new ExecutorException("Unknown statement type: " + ms.getStatementType());
    }

  }

        * 第三:循环插件生成代理对象,在方法最终执行前,先触发拦截器!该方法之前有过解析,参考MyBatis源码解析(三):初始化SqlSession第三步

// 循环插件生成StatementHandler的代理对象, 此处代理为循环代理
    statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);

    8,初始化数据库连接和 PreparedStatement 预编译平台

        * SimpleExecutor:prepareStatement()

private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
    Statement stmt;
    // 初始化数据库连接
    Connection connection = getConnection(statementLog);
    // 初始化PreparedStatement预编译平台
    stmt = handler.prepare(connection, transaction.getTimeout());
    // 封装Statement对象到StatementHandler处理器中
    handler.parameterize(stmt);
    return stmt;
  }

        * BaseExecutor:初始化数据库连接

protected Connection getConnection(Log statementLog) throws SQLException {
    Connection connection = transaction.getConnection();
    if (statementLog.isDebugEnabled()) {
      return ConnectionLogger.newInstance(connection, statementLog, queryStack);
    } else {
      return connection;
    }
  }
protected Connection getConnection(Log statementLog) throws SQLException {
    // 通过JdbcTransaction获取连接
    Connection connection = transaction.getConnection();
    if (statementLog.isDebugEnabled()) {
      return ConnectionLogger.newInstance(connection, statementLog, queryStack);
    } else {
      return connection;
    }
  }
protected void openConnection() throws SQLException {
    if (log.isDebugEnabled()) {
      log.debug("Opening JDBC Connection");
    }
    // dataSource已经封装好了数据库连接信息, 获取数据库连接
    connection = dataSource.getConnection();
    if (level != null) {
      connection.setTransactionIsolation(level.getLevel());
    }
    setDesiredAutoCommit(autoCommmit);
  }

        * BaseStatementHandler:初始化 PreparedStatement 预编译平台

public Statement prepare(Connection connection, Integer transactionTimeout) throws SQLException {
    ErrorContext.instance().sql(boundSql.getSql());
    Statement statement = null;
    try {
      // 从子类实现中获取最终的Statement
      // 此时子类实现为PreparedStatement
      statement = instantiateStatement(connection);
      setStatementTimeout(statement, transactionTimeout);
      setFetchSize(statement);
      return statement;
    } catch (SQLException e) {
      closeStatement(statement);
      throw e;
    } catch (Exception e) {
      closeStatement(statement);
      throw new ExecutorException("Error preparing statement.  Cause: " + e, e);
    }
  }
protected Statement instantiateStatement(Connection connection) throws SQLException {
    String sql = boundSql.getSql();
    if (mappedStatement.getKeyGenerator() instanceof Jdbc3KeyGenerator) {
      String[] keyColumnNames = mappedStatement.getKeyColumns();
      // 通过数据库连接, 获取预编译平台
      if (keyColumnNames == null) {
        return connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
      } else {
        return connection.prepareStatement(sql, keyColumnNames);
      }
    } else if (mappedStatement.getResultSetType() != null) {
      return connection.prepareStatement(sql, mappedStatement.getResultSetType().getValue(), ResultSet.CONCUR_READ_ONLY);
    } else {
      return connection.prepareStatement(sql);
    }
  }

    9,StatementHandler 处理器,进行最终结果集获取

        * 此时的 StatementHandler 对象是被拦截器插件代理后的代理对象,会通过动态代理方式进行执行,生成代理方法如下

public static Object wrap(Object target, Interceptor interceptor) {
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    Class<?> type = target.getClass();
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    // 存在有效插件
    if (interfaces.length > 0) {
      // 对target即executor进行代理
      // 外部循环调用, 则此时executor对象可能已经是代理对象
      // 允许对代理对象再次进行代理
      // 最终执行时, 装箱代理, 拆箱调用, 类似装饰者模式一层层进行处理
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }

        * StatementHandler.query()方法调用,会先执行 Plugin.invoke()方法

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
      if (methods != null && methods.contains(method)) {
        return interceptor.intercept(new Invocation(target, method, args));
      }
      return method.invoke(target, args);
    } catch (Exception e) {
      throw ExceptionUtil.unwrapThrowable(e);
    }
  }

        * 拦截器方法执行完成后,再最终调用 PreparedStatementHandler.query()方法,

public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
    // 转换Statement为JDBC原生的PreparedStatement
    PreparedStatement ps = (PreparedStatement) statement;
    // 通过JDBC底层执行, 并将执行结果封装到PreparedStatement中
    ps.execute();
    // resultSetHandler:结果集处理器, 对查询结果进行ORM映射
    return resultSetHandler.<E> handleResultSets(ps);
  }

    10,本篇博文只分析到获取结果集,ORM映射下一篇进行分析