一、先来看我定义的对象:
Account {
private Organization organization;
private int id;
getter/setter....
}
Organization{
private int id;
private String code;
getter/setter....
}
然后在mybatis的映射xml中有如下配置:
<sql id="accountProductColumns">
a.id,
a.organization_code AS "organization.code",
a.organization_id AS "organization.id"
</sql>
<select id="findList" resultType="Account">
SELECT
<include refid="accountProductColumns"/>
FROM t_ckcp_account a
WHERE a.del_flag = #{DEL_FLAG_NORMAL}
</select>
account对象中嵌套了对象organization,但是在数据库中表t_ckcp_account中保留的是organization中的属性,例如organization_code,organization_id, 对应的就是organization中的属性code和id。
在这种情况下,如果organization_code没有值,为null。那么在给account对象的属性organization赋值的时候,会因为code为null而赋值不成功。
解决方法是: 在Organization的get方法中new Organization:
Account {
private Organization organization;
private int id;
public Organization getOrganization(){
if organization == null this.organization = new Organization();
retrun this.organization
}
}
mybatis在给对象赋值的时候,首先会去调用类的get方法