例如,mybatis的mapper文件的内容如下,查询返回的是User对象:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.thb.mapper.UserMapper">
<select id="selectUser" resultType="com.thb.model.User">
select * from user where id = #{id}
</select>
</mapper>
定义了setter方法,mybatis返回对象会使用定义的setter方法给User 的name属性赋值
User对象的定义,其中对于属性name,定义了setName函数:
package com.thb.model;
public class User {
private int id;
private String name;
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
System.out.println("using setName method");
this.name = name;
}
}
运行输出如下,可以看到,赋值的时候使用了定义的setName方法
没有定义setter方法,mybatis返回对象会使用反射机制给User 的name属性赋值
将setName方法注释掉:
package com.thb.model;
public class User {
private int id;
private String name;
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
/*
public void setName(String name) {
System.out.println("using setName method");
this.name = name;
}*/
}
运行输出,可以看到,照样赋值成功: