現有如下需求:
某個類中存在其他類的對象,但在數據庫中只存了該對象的id。如果我們需要在查詢數據時將關聯對象一併查出,需要手動配置以下。
下面以註解的方式演示
給出兩個類:InputParam和Api類,InputParam中存在Api類的對象
public class InputParam {
private Integer inputParamId;
private Api api; //關聯Api類的對象
private String paramName;
private String paramDisplay;
private String paramType;
private Boolean optional;
private String paramDefault;
//省略getter&setter...
}
public class Api {
private Integer apiId;
private String component;
private String clientApi;
private String scribeDescribe;
private String clientApiVersion;
private Integer invokeTimeout;
private String authType;
private Boolean sessionRequire;
private Boolean openType;
//省略...
}
在InputParamMapper中,有一個用於查詢的方法:
@Select("SELECT * FROM inputParam WHERE inputParamId = #{id}")
@Results({
//查詢關聯對象
@Result(property = "api",
column = "apiId",
one = @One(select = "com.tuya.mapper.ApiMapper.selectById"))
})
InputParam selectById(@Param("id") int id);
在方法上使用@Select註解配置查詢所需要的SQL,使用@Results配置結果集,使用@Result配置某一個數據庫字段與實體類屬性之間的關係。由於其他屬性都是普通屬性,故不需要特殊處理。
爲了關聯查詢出Api對象,我們需要進行特別配置。使用@Result映射屬性與字段之間的關係,property是類中的屬性,column是數據庫中的字段,使用one表示獲取關聯關係中【一】的一方。在@One中,指定 查詢該對象的Mapper的方法(以column作爲參數的),這樣就能將該對象查出來並賦值給相應屬性。