解決mybatis查詢結果為null時,值被默認值替換問題
查詢結果為null時,值被默認值替換
問題:pojo種設置了一個默認值,當此字段查詢結果為空時,字段值變成了默認值0,經(jīng)過排查發(fā)現(xiàn),mybatis在賦值時并沒有調用set方法賦值,而是直接調用get方法,取了默認值
問題原因
原因是因為mybatis在給map賦值時,如果返回值不是基本數(shù)據(jù)類型,且返回值為null,就不會處理這個字段,不會將字段的值映射到map中。也就是說返回的map中是沒有這個字段的,當結果返回的時候,調用get方法,就直接調用了字段設置的默認值0
源碼:
解決辦法
在application.yml配置中添加配置call-setters-on-nulls: true,讓mybatis在給map參數(shù)映射的時候連null值也一并帶過來
mybatis查詢結果處理
處理核心流程
PreparedStatement的查詢結果需要進行映射
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); //處理結果集 }
處理結果集會用到結果集處理ResultSetHandler,他有兩個實現(xiàn)類:FastResultSetHandler和NestedResultSetHandler,前者用于普通結果集處理,后者用于嵌套結果集處理
就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查詢結果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處理該行數(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); // 處理結果 resultHandler.handleResult(resultContext); } } // 獲取行數(shù)據(jù) protected Object getRowValue(ResultSet rs, ResultMap resultMap, CacheKey rowKey, ResultColumnCache resultColumnCache) throws SQLException { // 實例化懶加載 final ResultLoaderMap lazyLoader = instantiateResultLoaderMap(); // 創(chuàng)建結果對象 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); // 執(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; // 返回結果對象 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) { // 設置屬性值 metaObject.setValue(property, value); foundValues = true; } } } } return foundValues; }
返回類型處理ResultHandler
在FastResultSetHandler#handleRowValues的resultHandler.handleResult(resultContext)中會調用結果處理器ResultHandler,他主要有下面兩個實現(xiàn)類
DefaultResultHandler主要用于查詢結果為resultType處理,DefaultMapResultHandler主要用于查詢結果為resultMap的處理
這里應為查詢結果為resultType,所以使用的是DefaultResultHandler#handleResult,主要是將處理后的結果值,放入結果列表中
public void handleResult(ResultContext context) { ? list.add(context.getResultObject()); }
字段類型處理TypeHandler
Mybatis主要使用TypeHadler進行返回結果字段類型的處理,他的主要子類是BaseTypeHandler, 預留了setNonNullParameter,getNullableResult等接口給子類實現(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等,分別用于處理不同的字段類型值
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
windows環(huán)境下mysql的解壓安裝及備份和還原
這篇文章主要介紹了windows環(huán)境下mysql的解壓安裝及備份和還原,需要的朋友可以參考下2017-09-09MySQL使用innobackupex備份連接服務器失敗的解決方法
這篇文章主要為大家詳細介紹了MySQL使用innobackupex備份連接服務器失敗的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-02-02MySql中使用INSERT INTO語句更新多條數(shù)據(jù)的例子
這篇文章主要介紹了MySql中使用INSERT INTO語句更新多條數(shù)據(jù)的例子,MySQL的特有語法,需要的朋友可以參考下2014-06-06