使用数据表:
创建对应实体类(此时员工类中属性名empName与员工表中字段名emp_name不一致):
package com.zyf.pojo;
// 员工类
public class Emp {
private Integer eid;
private String empName;
private Integer age;
private String sex;
private String email;
public Emp(){}
public Emp(Integer eid, String empName, Integer age, String sex, String email) {
this.eid = eid;
this.empName = empName;
this.age = age;
this.sex = sex;
this.email = email;
}
public Integer getEid() {
return eid;
}
public void setEid(Integer eid) {
this.eid = eid;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Emp{" +
"eid=" + eid +
", empName='" + empName + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", email='" + email + '\'' +
'}';
}
}
当查询字段名与对应实体类属性名不一致怎么办?
首先,我们来看看,当查询字段名与对应实体类属性名不一致时会发生什么。
package com.zyf.mapper;
public interface EmpMapper {
/**
* 查询所有的员工信息
*/
List<Emp> getAllEmp();
}
<mapper namespace="com.zyf.mapper.EmpMapper">
<select id="getAllEmp" resultType="Emp">
select * from t_emp;
select>
mapper>
测试代码:
@Test
public void testGetAllEmp(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
List<Emp> empList = empMapper.getAllEmp();
empList.forEach(emp -> System.out.println(emp));
}
运行结果:
我们发现程序并没有报错,而是查询字段值为空,因为此时属性名与字段名不一致导致映射时无法找到对应字段,程序就认为该值为null。
针对此类问题我们有三种解决方式:SQL语句设置别名、添加全局配置、使用resultMap自定义映射
(1)SQL语句设置别名
这种方法是给SQL语句中所查询的字段名设置一个别名,使它与实体类中的属性名保持一致(不常用)
<mapper namespace="com.zyf.mapper.EmpMapper">
<select id="getAllEmp" resultType="Emp">
select eid,emp_name as empName,age,sex,email from t_emp;
select>
mapper>
(2)添加全局配置
在MyBatis核心配置文件中使用setting标签,将_自动映射为驼峰
注意:该方法只适用于命名高度规范的情况,即数据表字段名使用( _ )下划线连接
<settings>
<setting name="mapUnderscoreToCamelCase" value="true">setting>
settings>
(3)使用resultMap自定义映射
使用resultMap为字段名与属性名自定义映射关系
<resultMap id="empResultMap" type="Emp">
<id property="eid" column="eid">id>
<result property="empName" column="emp_name">result>
<result property="age" column="age">result>
<result property="sex" column="sex">result>
<result property="email" column="email">result>
resultMap>
<select id="getAllEmp" resultMap="empResultMap">
select * from t_emp;
select>