问题现象:
- 通过mybatis查询数据库中的表记录,封装成javaBean, 本来属性名和字段名不相同的情况下,属性最后应该注入null的,结果能够正常注入。
javaBean:
public class Employee {
private Integer id;
private String empname;
private Integer age;
private Integer gender;
private String email;
private String loginName;
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", empname='" + empname + '\'' +
", age=" + age +
", gender=" + gender +
", email='" + email + '\'' +
", loginName='" + loginName + '\'' +
'}';
}
public Employee(Integer id, String empname, Integer age, Integer gender, String email, String loginName) {
this.id = id;
this.empname = empname;
this.age = age;
this.gender = gender;
this.email = email;
this.loginName = loginName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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 Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
- 表信息:
CREATE TABLE `employee` (
`id` int NOT NULL AUTO_INCREMENT,
`empname` varchar(20) NOT NULL,
`age` int DEFAULT NULL,
`gender` int DEFAULT NULL,
`email` varchar(20) DEFAULT NULL,
`login_name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb3
- mapper.xml中的sql语句:
<mapper namespace="com.tx.imapper.EmployeeMapper">
<select id="getEmployeeById" resultType="com.tx.bean.Employee">
select * from employee where id = #{id}
</select>
</mapper>
- Test类
public class Test {
public static SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@org.junit.Test
public void test(){
SqlSession sqlSession = sqlSessionFactory.openSession();
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
Employee emp = mapper.getEmployeeById(3);
System.out.println(emp); // Employee{id=1, empname='admin', age=40, gender=1, email='admin@qq.com', loginName='adminUser'}
sqlSession.close();
}
}
按照我的预估,loginName=null的,结果居然能够正常注入属性? 本来想测试resultMap的,结果我瞬间麻了。
刚开始我以为mybatis最新版本将驼峰规则默认改成true了,但来我甚至将loginName的属性名改成其他完全不相干名称,都能照样注入属性。
问题所在:
后来才发现,我的javaBean缺少空参构造器。添上空参构造器后,才会正常显示null。 具体原因不清楚以后有时间再看mybatis源码吧。
标签:封装,String,gender,public,email,mybatis,Integer,id,属性 From: https://www.cnblogs.com/tanxin1989/p/16912040.html