现有如下需求:
某个类中存在其他类的对象,但在数据库中只存了该对象的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作为参数的),这样就能将该对象查出来并赋值给相应属性。