广告
返回顶部
首页 > 资讯 > 数据库 >解决mybatis查询结果为null时,值被默认值替换问题
  • 506
分享到

解决mybatis查询结果为null时,值被默认值替换问题

mybatis查询结果mybatis查询结果为null值被默认值替换 2022-07-07 11:07:07 506人浏览 泡泡鱼
摘要

目录查询结果为null时,值被默认值替换问题原因解决办法mybatis查询结果处理处理核心流程返回类型处理ResultHandler字段类型处理TypeHandler查询结果为null时,值被默认值替换 问题:pojo种

查询结果为null时,值被默认值替换

问题:pojo种设置了一个默认值,当此字段查询结果为空时,字段值变成了默认值0,经过排查发现,mybatis在赋值时并没有调用set方法赋值,而是直接调用get方法,取了默认值

解决mybatis查询结果为null时,值被默认值替换问题

问题原因

原因是因为mybatis在给map赋值时,如果返回值不是基本数据类型,且返回值为null,就不会处理这个字段,不会将字段的值映射到map中。也就是说返回的map中是没有这个字段的,当结果返回的时候,调用get方法,就直接调用了字段设置的默认值0

源码:

解决mybatis查询结果为null时,值被默认值替换问题

解决办法

在application.yml配置中添加配置call-setters-on-nulls: true,让mybatis在给map参数映射的时候连null值也一并带过来

解决mybatis查询结果为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等,分别用于处理不同的字段类型值

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

您可能感兴趣的文档:

--结束END--

本文标题: 解决mybatis查询结果为null时,值被默认值替换问题

本文链接: https://www.lsjlt.com/news/33241.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作