最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

解決mybatis查詢結(jié)果為null時(shí),值被默認(rèn)值替換問題

 更新時(shí)間:2022年07月07日 09:59:50   作者:一個(gè)包子走天下  
這篇文章主要介紹了解決mybatis查詢結(jié)果為null時(shí),值被默認(rèn)值替換問題。具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

查詢結(jié)果為null時(shí),值被默認(rèn)值替換

問題:pojo種設(shè)置了一個(gè)默認(rèn)值,當(dāng)此字段查詢結(jié)果為空時(shí),字段值變成了默認(rèn)值0,經(jīng)過排查發(fā)現(xiàn),mybatis在賦值時(shí)并沒有調(diào)用set方法賦值,而是直接調(diào)用get方法,取了默認(rèn)值

問題原因

原因是因?yàn)閙ybatis在給map賦值時(shí),如果返回值不是基本數(shù)據(jù)類型,且返回值為null,就不會處理這個(gè)字段,不會將字段的值映射到map中。也就是說返回的map中是沒有這個(gè)字段的,當(dāng)結(jié)果返回的時(shí)候,調(diào)用get方法,就直接調(diào)用了字段設(shè)置的默認(rèn)值0

源碼:

解決辦法

在application.yml配置中添加配置call-setters-on-nulls: true,讓mybatis在給map參數(shù)映射的時(shí)候連null值也一并帶過來

mybatis查詢結(jié)果處理

處理核心流程

PreparedStatement的查詢結(jié)果需要進(jìn)行映射

public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
? PreparedStatement ps = (PreparedStatement) statement; // 裝換preparedStatement
? ps.execute(); // 執(zhí)行SQL
? return resultSetHandler.<E> handleResultSets(ps); //處理結(jié)果集
}

處理結(jié)果集會用到結(jié)果集處理ResultSetHandler,他有兩個(gè)實(shí)現(xiàn)類:FastResultSetHandler和NestedResultSetHandler,前者用于普通結(jié)果集處理,后者用于嵌套結(jié)果集處理

就FastResultSetHandler而言,handleResultSets的執(zhí)行步驟為

public List<Object> handleResultSets(Statement stmt) throws SQLException {
  final List<Object> multipleResults = new ArrayList<Object>();
  final List<ResultMap> resultMaps = mappedStatement.getResultMaps(); // sql查詢結(jié)果map
  int resultMapCount = resultMaps.size();
  int resultSetCount = 0;
  ResultSet rs = stmt.getResultSet(); // 結(jié)果集
  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); // 校驗(yàn)結(jié)果集
  while (rs != null && resultMapCount > resultSetCount) {
    final ResultMap resultMap = resultMaps.get(resultSetCount);
    ResultColumnCache resultColumnCache = new ResultColumnCache(rs.getMetaData(), configuration);
    handleResultSet(rs, resultMap, multipleResults, resultColumnCache);// 處理結(jié)果集
    rs = getNextResultSet(stmt); // 獲取下一個(gè)結(jié)果集
    cleanUpAfterHandlingResultSet();
    resultSetCount++;
  }
  return collapseSingleResultList(multipleResults); // 單個(gè)結(jié)果集轉(zhuǎn)換為list返回
}
// 處理每行結(jié)果
protected void handleResultSet(ResultSet rs, ResultMap resultMap, List<Object> multipleResults, ResultColumnCache resultColumnCache) throws SQLException {
    try {
      if (resultHandler == null) {
        DefaultResultHandler defaultResultHandler = new DefaultResultHandler(objectFactory);
          // 使用默認(rèn)DefaultResultHandler處理該行數(shù)據(jù)
        handleRowValues(rs, resultMap, defaultResultHandler, rowBounds, resultColumnCache);
        multipleResults.add(defaultResultHandler.getResultList());
      } else {
        handleRowValues(rs, resultMap, resultHandler, rowBounds, resultColumnCache);
      }
    } finally {
      closeResultSet(rs); // close resultsets
    }
}
// 處理每行數(shù)據(jù)
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);
        // 處理結(jié)果
      resultHandler.handleResult(resultContext);
    }
}
// 獲取行數(shù)據(jù)
protected Object getRowValue(ResultSet rs, ResultMap resultMap, CacheKey rowKey, ResultColumnCache resultColumnCache) throws SQLException {
    // 實(shí)例化懶加載
    final ResultLoaderMap lazyLoader = instantiateResultLoaderMap();
    // 創(chuàng)建結(jié)果對象
    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())) { // 自動映射結(jié)果到字段
          // 獲取未映射的列名
        final List<String> unmappedColumnNames = resultColumnCache.getUnmappedColumnNames(resultMap, null); 
          // 執(zhí)行自動映射
        foundValues = applyAutomaticMappings(rs, unmappedColumnNames, metaObject, null, resultColumnCache) || foundValues;
      }
        // 獲取已映射的列名
      final List<String> mappedColumnNames = resultColumnCache.getMappedColumnNames(resultMap, null);
        // 執(zhí)行屬性映射
      foundValues = applyPropertyMappings(rs, resultMap, mappedColumnNames, metaObject, lazyLoader, null) || foundValues;
      foundValues = (lazyLoader != null && lazyLoader.size() > 0) || foundValues;
      resultObject = foundValues ? resultObject : null;
        // 返回結(jié)果對象
      return resultObject;
    }
    return resultObject;
}
// 執(zhí)行自動映射
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) {
              // 設(shè)置屬性值
            metaObject.setValue(property, value);
            foundValues = true;
          }
        }
      }
    }
    return foundValues;
  }

返回類型處理ResultHandler

在FastResultSetHandler#handleRowValues的resultHandler.handleResult(resultContext)中會調(diào)用結(jié)果處理器ResultHandler,他主要有下面兩個(gè)實(shí)現(xiàn)類

DefaultResultHandler主要用于查詢結(jié)果為resultType處理,DefaultMapResultHandler主要用于查詢結(jié)果為resultMap的處理

這里應(yīng)為查詢結(jié)果為resultType,所以使用的是DefaultResultHandler#handleResult,主要是將處理后的結(jié)果值,放入結(jié)果列表中

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

字段類型處理TypeHandler

Mybatis主要使用TypeHadler進(jìn)行返回結(jié)果字段類型的處理,他的主要子類是BaseTypeHandler, 預(yù)留了setNonNullParameter,getNullableResult等接口給子類實(shí)現(xiàn) 

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等,分別用于處理不同的字段類型值

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • MySQL中的ORDER BY問題

    MySQL中的ORDER BY問題

    這篇文章主要介紹了MySQL中的ORDER BY問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • MySQL數(shù)據(jù)庫表內(nèi)容的增刪查改操作實(shí)例詳解

    MySQL數(shù)據(jù)庫表內(nèi)容的增刪查改操作實(shí)例詳解

    對于刪除操作來說,是將表單個(gè)或者多個(gè)數(shù)據(jù)進(jìn)行刪除,而截?cái)鄤t是對整個(gè)表進(jìn)行操作,會將整個(gè)表數(shù)據(jù)都清除,本文給大家介紹MySQL數(shù)據(jù)庫表內(nèi)容的增刪查改操作大全,感興趣的朋友一起看看吧
    2025-04-04
  • MySQL exists 和in 詳解及區(qū)別

    MySQL exists 和in 詳解及區(qū)別

    本文章向大家介紹MySQL exists 和in 使用方法以及他們之間的區(qū)別,需要的朋友可以參考下
    2017-01-01
  • Mysql存儲過程、觸發(fā)器、事件調(diào)度器使用入門指南

    Mysql存儲過程、觸發(fā)器、事件調(diào)度器使用入門指南

    存儲過程(Stored Procedure)是一種在數(shù)據(jù)庫中存儲復(fù)雜程序的數(shù)據(jù)庫對象。為了完成特定功能的SQL語句集,經(jīng)過編譯創(chuàng)建并保存在數(shù)據(jù)庫中,本文給大家介紹Mysql存儲過程、觸發(fā)器、事件調(diào)度器使用入門指南,感興趣的朋友一起看看吧
    2022-01-01
  • mybatis-plus如何使用sql的date_format()函數(shù)查詢數(shù)據(jù)

    mybatis-plus如何使用sql的date_format()函數(shù)查詢數(shù)據(jù)

    這篇文章主要給大家介紹了關(guān)于mybatis-plus如何使用sql的date_format()函數(shù)查詢數(shù)據(jù)的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2023-02-02
  • MySQL中utf8mb4排序規(guī)則示例

    MySQL中utf8mb4排序規(guī)則示例

    本文主要介紹了MySQL中utf8mb4排序規(guī)則,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-07-07
  • MySql修改數(shù)據(jù)庫編碼為UTF8避免造成亂碼問題

    MySql修改數(shù)據(jù)庫編碼為UTF8避免造成亂碼問題

    mysql 創(chuàng)建數(shù)據(jù)庫時(shí)指定編碼很重要,很多開發(fā)者都使用了默認(rèn)編碼,亂碼問題可是防不勝防,下面與大家分享下通過修改數(shù)據(jù)庫默認(rèn)編碼方式為UTF8來減少數(shù)據(jù)庫創(chuàng)建時(shí)的設(shè)置,避免因粗心造成的亂碼問題
    2013-06-06
  • CentOS 6.5安裝mysql5.7教程

    CentOS 6.5安裝mysql5.7教程

    這篇文章主要為大家詳細(xì)介紹了CentOS 6.5安裝mysql5.7教程,包括mysal舊版本的卸載、新版本的升級,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-04-04
  • SQL的substring_index()用法實(shí)例(MySQL字符串截取)

    SQL的substring_index()用法實(shí)例(MySQL字符串截取)

    substring_index?(字符串,分隔符,序號),主要作用是用于截取目標(biāo)字符串,下面這篇文章主要給大家介紹了關(guān)于SQL中substring_index()用法(MySQL字符串截取)的相關(guān)資料,需要的朋友可以參考下
    2023-01-01
  • MySQL 5.5的max_allowed_packet屬性的修改方法

    MySQL 5.5的max_allowed_packet屬性的修改方法

    今天在部署一個(gè)實(shí)驗(yàn)系統(tǒng)的時(shí)候,報(bào)錯(cuò)提示需要修改一下MySQL的配置文件,在修改的時(shí)候是有技巧的,大家可以參考下本文嘗試操作下
    2013-08-08

最新評論

志丹县| 绥棱县| 新津县| 松阳县| 北碚区| 富川| 宜川县| 临城县| 铁力市| 马山县| 大关县| 当雄县| 长顺县| 宜川县| 汉阴县| 巴青县| 贵州省| 西平县| 崇仁县| 孟州市| 云安县| 高唐县| 横山县| 衡东县| 连云港市| 安溪县| 土默特右旗| 六安市| 克山县| 道真| 滦平县| 宜兰市| 江孜县| 商丘市| 河间市| 自贡市| 敦化市| 怀柔区| 镇巴县| 漳平市| 白朗县|