我们在设计数据库表的时候, 一个字段多个单词,用"_"连接, 如, user_name.
而我们在代码中创建实体类的时候, 通常用驼峰命名法, 如 : userName.
这就造成了我们在写sql的时候, 因为名称不同, 找不到数据, 报空指针异常.
为了解决问题,有以下两种方式:
(一) 使用AS, 作为别名
xml文件:
<select id="getUserList" resultType="dto.UserDto">
select id, user_id as userId, user_name as userName, phone, enable, created
from t_user
where enable =1
</select>
对应的实体类:
package dto;
@Setter
@Getter
public class UserDto{
private int id;
private String userId;
private String userName;
private String phone;
private int enable;
}
这种方法, 最常用, 但是如果如果对象的字段较多, 每次都要写AS别名, 就会比较麻烦,这就可以考虑第二种方法.
(二) 封装, 封装sql返回的对象
xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.mybatis.UserMybatis">
//封装sql返回的对象
<resultMap id="UserResultMap" type="dto.UserDto">
<result column="id" property="id" jdbcType="INT"/>
<result column="user_id" property="userId" jdbcType="VARCHAR"/>
<result column="user_name" property="userName" jdbcType="VARCHAR"/>
<result column="phone" property="phone" jdbcType="VARCHAR"/>
<result column="enable" property="enable" jdbcType="TINYINT"/>
</resultMap>
<select id="getUserList" resultMap="UserResultMap">
select id, user_id, user_name, phone, enable, created
from t_user
where enable =1
</select>
</mapper>
对应的实体类:
package dto;
@Setter
@Getter
public class UserDto{
private int id;
private String userId;
private String userName;
private String phone;
private int enable;
}
注意点:
后期如果实体类字段增加或减少, 在xml文件中的sql封装对象也要相应的增加或减少.