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

Android Room数据库嵌套关联查询返回Null Data问题求助

问题原因

你的嵌套关联配置存在错误:OrderWithLineItems 中 @Relation 手动指定了 entity = LineItem::class,导致Room仅会查询LineItem表填充ProductAndLineItem的内嵌LineItem字段,不会触发ProductAndLineItem内部定义的Product关联查询。

解决方案

  1. 修改OrderWithLineItems类的@Relation注解,移除冗余的entity参数即可:
data class OrderWithLineItems(
    @Embedded var order: Order,
    @Relation(
        parentColumn = "orderId",
        entityColumn = "orderId"
    )
    val lineItemList: List<ProductAndLineItem>
)

Room会自动从ProductAndLineItem的@Embedded字段识别关联实体为LineItem,同时触发内部的Product关联查询,你原有代码中已经加了@Transaction注解,满足嵌套关联多查询的事务要求。

  1. 可选优化:ProductAndLineItem中lineItem字段无需定义为可空类型,关联查询时LineItem一定存在,可改为非空类型避免不必要的空判断:
data class ProductAndLineItem(
    @Embedded val lineItem: LineItem,
    @Relation(
        parentColumn = "productId",
        entityColumn = "productId"
    )
    val product: Product?
)
  1. 若修改后仍存在问题,检查你的Room依赖版本:嵌套关联从Room 2.2.0版本开始支持,建议升级到2.4.0及以上稳定版本规避版本兼容问题。

内容的提问来源于stack exchange,提问作者hieuwu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:57:01