MyBatis 查询结果自动封装为map,出现null而没有字段名
- 问题
1 | select a, b, c from table |
- 原因:
org.apache.ibatis.executor.resultset.DefaultResultSetHandler 类下面找到 getRowValue
方法
1 | private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix) throws SQLException { |
在对 rowValue 赋值的时候,会去判断语句查询是否有值 或者 configuration.isReturnInstanceForEmptyRow() 这个配置项是否为true,如果前面都是false的话,就置为null,也就是最后返回结果里null的原因
参数 | 含义 | 有效值 | 默认值 |
---|---|---|---|
callSettersOnNulls | 指定当结果集中值为 null 的时候是否调用映射对象的 setter(map 对象时为 put)方法,这在依赖于 Map.keySet() 或 null 值进行初始化时比较有用。注意基本类型(int、boolean 等)是不能设置成 null 的。 | true ` | ` false |
returnInstanceForEmptyRow | 当返回行的所有列都是空时,MyBatis默认返回 null。 当开启这个设置时,MyBatis会返回一个空实例。 请注意,它也适用于嵌套的结果集(如集合或关联)。(新增于 3.4.2) | true ` | ` false |
- 解决:
在 mybatis-config.xml 文件里添加两个参数
1 | <configuration> |
在 application.properties 里去指定 mybatis-config.xml 的路径
1 | mybatis.config-location: mybatis-config.xml |
或者在注册sqlFactory的时候,去指定configLocation
1 | bean.setConfigLocation(new DefaultResourceLoader().getResource("classpath:mybatis-config.xml")); |