mybatis查询结果为null,值被默认值替换
一个包子走天下 人气:0查询结果为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等,分别用于处理不同的字段类型值
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
加载全部内容