现象
数据库中字段有值,但接口返回对象对应字段为 null。
SQL 单独在数据库执行是正常的。
原始SQL
<select id="selectUser" resultType="com.example.User">
select user_id, user_name
from user
where user_id = #{id}
</select>
实体类:
public class User {
private Long userId;
private String userName;
}
查询后发现 userName 为 null。
排查
数据库字段为:
实体类为:
MyBatis 默认不会自动把下划线转为驼峰。
解决方式一
开启驼峰映射:
mybatis:
configuration:
map-underscore-to-camel-case: true
或在配置类中:
configuration.setMapUnderscoreToCamelCase(true);
解决方式二
使用别名:
<select id="selectUser" resultType="com.example.User">
select user_id as userId,
user_name as userName
from user
where user_id = #{id}
</select>
补充
如果使用 resultMap,需要确认 property 和 column 是否一一对应:
<resultMap id="userMap" type="com.example.User">
<result property="userId" column="user_id"/>
<result property="userName" column="user_name"/>
</resultMap>
字段名和实体属性不匹配时,不会报错,只会映射失败。