解决方法
Mybatis配置类中获取SqlSessionFactoryBean中配置:
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
configuration.setCallSettersOnNulls(true);
configuration.setReturnInstanceForEmptyRow(true);
gpSqlSessionFactory.setConfiguration(configuration);
很多网上教程只配置了configuration.setCallSettersOnNulls(true),没有configuration.setReturnInstanceForEmptyRow(true);会导致筛选字段都为NULL时会封装不上的问题,所以一定要两个都要配置。
源码分析
在org.apache.ibatis.executor.resultset.DefaultResultSetHandler类中方法:
private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap) throws SQLException {
final ResultLoaderMap lazyLoader = new ResultLoaderMap();
Object rowValue = createResultObject(rsw, resultMap, lazyLoader, null);
if (rowValue != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) {
final MetaObject metaObject = configuration.newMetaObject(rowValue);
boolean foundValues = this.useConstructorMappings;
if (shouldApplyAutomaticMappings(resultMap, false)) {
foundValues = applyAutomaticMappings(rsw, resultMap, metaObject, null) || foundValues;
}
foundValues = applyPropertyMappings(rsw, resultMap, metaObject, lazyLoader, null) || foundValues;
foundValues = lazyLoader.size() > 0 || foundValues;
//这里会拿上面的配置configuration.setReturnInstanceForEmptyRow(true);但foundValues为false也会封装结果
rowValue = foundValues || configuration.isReturnInstanceForEmptyRow() ? rowValue : null;
}
return rowValue;
}
private boolean applyAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, String columnPrefix) throws SQLException {
List<UnMappedColumnAutoMapping> autoMapping = createAutomaticMappings(rsw, resultMap, metaObject, columnPrefix);
boolean foundValues = false;
if (!autoMapping.isEmpty()) {
for (UnMappedColumnAutoMapping mapping : autoMapping) {
final Object value = mapping.typeHandler.getResult(rsw.getResultSet(), mapping.column);
if (value != null) {
foundValues = true;
}
//这里会拿我们上面设置configuration.setCallSettersOnNulls(true);这个配置当foundValues为false也会将值保存
if (value != null || (configuration.isCallSettersOnNulls() && !mapping.primitive)) {
// gcode issue #377, call setter on nulls (value is not 'found')
metaObject.setValue(mapping.property, value);
}
}
}
return foundValues;
}
以上就是我遇到查询为NULL时,Mybatis不封装的解决方法,如还有其他方式还请各网友留言,蟹蟹!