MyBatis查询结果处理

1 处理核心流程

PreparedStatement的查询结果需要进行映射

public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
  PreparedStatement ps = (PreparedStatement) statement; // 装换preparedStatement
  ps.execute(); // 执行SQL
  return resultSetHandler.<E> handleResultSets(ps); //处理结果集
}

处理结果集会用到结果集处理ResultSetHandler,他有两个实现类:FastResultSetHandler和NestedResultSetHandler,前者用于普通结果集处理,后者用于嵌套结果集处理

就FastResultSetHandler而言,handleResultSets的执行步骤为

public List<Object> handleResultSets(Statement stmt) throws SQLException {
  final List<Object> multipleResults = new ArrayList<Object>();
  final List<ResultMap> resultMaps = mappedStatement.getResultMaps(); // sql查询结果map
  int resultMapCount = resultMaps.size();
  int resultSetCount = 0;
  ResultSet rs = stmt.getResultSet(); // 结果集

  while (rs == null) {
    // move forward to get the first resultset in case the driver
    // doesn't return the resultset as the first result (HSQLDB 2.1)
    if (stmt.getMoreResults()) {
      rs = stmt.getResultSet();
    } else {
      if (stmt.getUpdateCount() == -1) {
        // no more results.  Must be no resultset
        break;
      }
    }
  }

  validateResultMapsCount(rs, resultMapCount); // 校验结果集
  while (rs != null && resultMapCount > resultSetCount) {
    final ResultMap resultMap = resultMaps.get(resultSetCount);
    ResultColumnCache resultColumnCache = new ResultColumnCache(rs.getMetaData(), configuration);
    handleResultSet(rs, resultMap, multipleResults, resultColumnCache);// 处理结果集
    rs = getNextResultSet(stmt); // 获取下一个结果集
    cleanUpAfterHandlingResultSet();
    resultSetCount++;
  }
  return collapseSingleResultList(multipleResults); // 单个结果集转换为list返回
}

// 处理每行结果
protected void handleResultSet(ResultSet rs, ResultMap resultMap, List<Object> multipleResults, ResultColumnCache resultColumnCache) throws SQLException {
    try {
      if (resultHandler == null) {
        DefaultResultHandler defaultResultHandler = new DefaultResultHandler(objectFactory);
          // 使用默认DefaultResultHandler处理该行数据
        handleRowValues(rs, resultMap, defaultResultHandler, rowBounds, resultColumnCache);
        multipleResults.add(defaultResultHandler.getResultList());
      } else {
        handleRowValues(rs, resultMap, resultHandler, rowBounds, resultColumnCache);
      }
    } finally {
      closeResultSet(rs); // close resultsets
    }
}

// 处理每行数据
protected void handleRowValues(ResultSet rs, ResultMap resultMap, ResultHandler resultHandler, RowBounds rowBounds, ResultColumnCache resultColumnCache) throws SQLException {
    final DefaultResultContext resultContext = new DefaultResultContext();
    skipRows(rs, rowBounds);
    while (shouldProcessMoreRows(rs, resultContext, rowBounds)) {
      final ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(rs, resultMap, null);
        // 获取行值
      Object rowValue = getRowValue(rs, discriminatedResultMap, null, resultColumnCache);
        // 添加到上下文
      resultContext.nextResultObject(rowValue);
        // 处理结果
      resultHandler.handleResult(resultContext);
    }
}

// 获取行数据
protected Object getRowValue(ResultSet rs, ResultMap resultMap, CacheKey rowKey, ResultColumnCache resultColumnCache) throws SQLException {
    // 实例化懒加载
    final ResultLoaderMap lazyLoader = instantiateResultLoaderMap();
    // 创建结果对象
    Object resultObject = createResultObject(rs, resultMap, lazyLoader, null, resultColumnCache);
    if (resultObject != null && !typeHandlerRegistry.hasTypeHandler(resultMap.getType())) {
        // 新建元对象
      final MetaObject metaObject = configuration.newMetaObject(resultObject);
      boolean foundValues = resultMap.getConstructorResultMappings().size() > 0;
      if (!AutoMappingBehavior.NONE.equals(configuration.getAutoMappingBehavior())) { // 自动映射结果到字段
          // 获取未映射的列名
        final List<String> unmappedColumnNames = resultColumnCache.getUnmappedColumnNames(resultMap, null); 
          // 执行自动映射
        foundValues = applyAutomaticMappings(rs, unmappedColumnNames, metaObject, null, resultColumnCache) || foundValues;
      }
        // 获取已映射的列名
      final List<String> mappedColumnNames = resultColumnCache.getMappedColumnNames(resultMap, null);
        // 执行属性映射
      foundValues = applyPropertyMappings(rs, resultMap, mappedColumnNames, metaObject, lazyLoader, null) || foundValues;
      foundValues = (lazyLoader != null && lazyLoader.size() > 0) || foundValues;
      resultObject = foundValues ? resultObject : null;
        // 返回结果对象
      return resultObject;
    }
    return resultObject;
}

// 执行自动映射
protected boolean applyAutomaticMappings(ResultSet rs, List<String> unmappedColumnNames, MetaObject metaObject, String columnPrefix, ResultColumnCache resultColumnCache) throws SQLException {
    boolean foundValues = false;
    for (String columnName : unmappedColumnNames) {
        // 列名
      String propertyName = columnName;
      if (columnPrefix != null && columnPrefix.length() > 0) {
        // When columnPrefix is specified,
        // ignore columns without the prefix.
        if (columnName.startsWith(columnPrefix)) {
          propertyName = columnName.substring(columnPrefix.length());
        } else {
          continue;
        }
      }
        // 获取属性值
      final String property = metaObject.findProperty(propertyName, configuration.isMapUnderscoreToCamelCase());
      if (property != null) {
          // 获取属性值的类型
        final Class<?> propertyType = metaObject.getSetterType(property);
        if (typeHandlerRegistry.hasTypeHandler(propertyType)) {
            // 获取属性值的类型处理器
          final TypeHandler<?> typeHandler = resultColumnCache.getTypeHandler(propertyType, columnName);
            // 由类型处理器获取属性值
          final Object value = typeHandler.getResult(rs, columnName);
          if (value != null) {
              // 设置属性值
            metaObject.setValue(property, value);
            foundValues = true;
          }
        }
      }
    }
    return foundValues;
  }

2 返回类型处理ResultHandler

在FastResultSetHandler#handleRowValues的resultHandler.handleResult(resultContext)中会调用结果处理器ResultHandler,他主要有下面两个实现类

DefaultResultHandler主要用于查询结果为resultType处理,DefaultMapResultHandler主要用于查询结果为resultMap的处理

这里应为查询结果为resultType,所以使用的是DefaultResultHandler#handleResult,主要是将处理后的结果值,放入结果列表中

public void handleResult(ResultContext context) {
  list.add(context.getResultObject());
}

3 字段类型处理TypeHandler

Mybatis主要使用TypeHadler进行返回结果字段类型的处理,他的主要子类是BaseTypeHandler, 预留了setNonNullParameter,getNullableResult等接口给子类实现

public abstract class BaseTypeHandler<T> extends TypeReference<T> implements TypeHandler<T> {

  protected Configuration configuration;

  public void setConfiguration(Configuration c) {
    this.configuration = c;
  }

  public void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
    if (parameter == null) {
      if (jdbcType == null) {
        throw new TypeException("JDBC requires that the JdbcType must be specified for all nullable parameters.");
      }
      try {
        ps.setNull(i, jdbcType.TYPE_CODE);
      } catch (SQLException e) {
        throw new TypeException("Error setting null for parameter #" + i + " with JdbcType " + jdbcType + " . " +
              "Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. " +
              "Cause: " + e, e);
      }
    } else {
      setNonNullParameter(ps, i, parameter, jdbcType);
    }
  }

  public T getResult(ResultSet rs, String columnName) throws SQLException {
    T result = getNullableResult(rs, columnName);
    if (rs.wasNull()) {
      return null;
    } else {
      return result;
    }
  }

  public T getResult(ResultSet rs, int columnIndex) throws SQLException {
    T result = getNullableResult(rs, columnIndex);
    if (rs.wasNull()) {
      return null;
    } else {
      return result;
    }
  }

  public T getResult(CallableStatement cs, int columnIndex) throws SQLException {
    T result = getNullableResult(cs, columnIndex);
    if (cs.wasNull()) {
      return null;
    } else {
      return result;
    }
  }

  public abstract void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;
  public abstract T getNullableResult(ResultSet rs, String columnName) throws SQLException;
  public abstract T getNullableResult(ResultSet rs, int columnIndex) throws SQLException;
  public abstract T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException;

}

他的子类主要有StringTypeHandler、BOOleanTypeHandler等,分别用于处理不同的字段类型值

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值