Mybatis框架實體類欄位與資料庫表字段不一致導致查詢該欄位的值一直為null
阿新 • • 發佈:2019-02-12
實體類如下所示:
public class BasicInfo {
private Integer basic_id;
private String name;
private String gender;
private Integer age;
private String address;
private String email;
private String phone;
private String school;
private String introduce;
//……(此處省略setter和getter方法)
}
實體類對映的資料庫表如下所示:
create table `basic_info`
(
`basic_id` int not null auto_increment,
`name` varchar(16),
`gender` varchar(4) ,
`age` int default '0',
`address` varchar(64),
`email` varchar(32),
`tel` varchar(16),
`school` varchar(64),
`introdece` varchar(1024),
`user_id` int,
primary key (`basic_id`),
key `fk_basicinfo_account` (`user_id`),
constraint `fk_basicinfo_account` foreign key (`user_id`) references `account` (`id`)
) engine=InnoDB default charset=utf8 |
使用Mybatis查詢配置如下所示
<select id="queryById" parameterType="int" resultType="BasicInfo">
select basic_id,name,gender, age,school,tel
from basic_info
where basic_id = #{id}
</select>
主要查詢java程式碼:
@Override
public BasicInfo queryById(Integer id) {
BasicInfo basicInfo = null;
SqlSession session = MybatisSessionManage.getSqlSessionAutoCommit();
basicInfo = session.selectOne("basicinfo.queryById", id);
return basicInfo;
}
查詢結果:
解決方法
方法1
在查詢中含有表字段與物件欄位不對應的,可以在查詢語句用as 物件欄位名解決欄位不一致不自動封裝的問題
<select id="queryById" parameterType="int" resultType="BasicInfo">
select basic_id,name,gender, age,school,tel as phone
from basic_info
where basic_id = #{id}
</select>
方法2
修改select元素中resultType
屬性 為 resultMap
屬性並建立返回的map型別
<resultMap id="basicInfoMapper" type="BasicInfo">
<id column="basic_info" property="basic_id" />
<result column="name" property="name" />
<result column="gender" property="gender" />
<result column="age" property="age" />
<result column="address" property="address" />
<result column="email" property="email" />
<result column="tel" property="phone" />
<result column="school" property="school" />
<result column="introduce" property="introduce" />
</resultMap>
<select id="queryByIdAndMapper" resultMap="basicInfoMapper" parameterType="int">
select basic_id,name,gender, age,school,tel
from basic_info
where basic_id = #{id}
</select>
執行結果: