是否可通过Room原生机制直接映射该嵌套关联查询场景?
Room 嵌套关联映射解决方案
Room 原生支持你需要的多层嵌套关联映射机制,你遇到的报错是因为 @Relation 注解未显式指定关联的数据库实体类。
错误原因
@Relation 默认会将标注的字段类型当做数据库实体/视图进行解析,你的PropertyWithAddress是自定义业务POJO类,不是数据库实体,所以触发了类型校验错误。
修复方案
只需要在DetailedCustomerInformation的property字段的@Relation注解中,显式指定关联的实体类为Property::class即可,修复后的代码如下:
data class DetailedCustomerInformation( @Embedded val customer: Customer, @Relation(parentColumn = "addressId", entityColumn = "id") val address: Address, @Relation( parentColumn = "propertyId", entityColumn = "id", entity = Property::class // 显式指定关联的数据库实体 ) val property: PropertyWithAddress ) : Serializable
映射规则说明
- 显式指定
entity参数后,Room会明确知道该字段的关联查询主表为Property表 - Room会自动递归解析
PropertyWithAddress内部的@Embedded和@Relation注解,自动完成Property和对应Address的查询、对象组装,不需要你手动编写多表联查SQL和手动赋值。
注意事项
- 确保
Customer实体存在propertyId、addressId两个外键字段 - 确保
Property实体存在addressId外键字段
内容的提问来源于stack exchange,提问作者Luis Fernando
相关产品推荐
相关产品推荐

