You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

是否可通过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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 12:39:04