mybatis給物件賦值
阿新 • • 發佈:2019-01-08
一、先來看我定義的物件:
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方法