首頁 > 軟體

解決mybatis查詢結果為null時,值被預設值替換問題

2022-07-07 14:04:57

查詢結果為null時,值被預設值替換

問題:pojo種設定了一個預設值,當此欄位查詢結果為空時,欄位值變成了預設值0,經過排查發現,mybatis在賦值時並沒有呼叫set方法賦值,而是直接呼叫get方法,取了預設值

問題原因

原因是因為mybatis在給map賦值時,如果返回值不是基本資料型別,且返回值為null,就不會處理這個欄位,不會將欄位的值對映到map中。也就是說返回的map中是沒有這個欄位的,當結果返回的時候,呼叫get方法,就直接呼叫了欄位設定的預設值0

原始碼:

解決辦法

在application.yml設定中新增設定call-setters-on-nulls: true,讓mybatis在給map引數對映的時候連null值也一併帶過來

mybatis查詢結果處理

處理核心流程

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;
  }

返回型別處理ResultHandler

在FastResultSetHandler#handleRowValues的resultHandler.handleResult(resultContext)中會呼叫結果處理器ResultHandler,他主要有下面兩個實現類

DefaultResultHandler主要用於查詢結果為resultType處理,DefaultMapResultHandler主要用於查詢結果為resultMap的處理

這裡應為查詢結果為resultType,所以使用的是DefaultResultHandler#handleResult,主要是將處理後的結果值,放入結果列表中

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

欄位型別處理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等,分別用於處理不同的欄位型別值

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com