Android Room数据库嵌套关联查询返回Null Data问题求助
问题原因
你的嵌套关联配置存在错误:OrderWithLineItems 中 @Relation 手动指定了 entity = LineItem::class,导致Room仅会查询LineItem表填充ProductAndLineItem的内嵌LineItem字段,不会触发ProductAndLineItem内部定义的Product关联查询。
解决方案
- 修改
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注解,满足嵌套关联多查询的事务要求。
- 可选优化:
ProductAndLineItem中lineItem字段无需定义为可空类型,关联查询时LineItem一定存在,可改为非空类型避免不必要的空判断:
data class ProductAndLineItem( @Embedded val lineItem: LineItem, @Relation( parentColumn = "productId", entityColumn = "productId" ) val product: Product? )
- 若修改后仍存在问题,检查你的Room依赖版本:嵌套关联从Room 2.2.0版本开始支持,建议升级到2.4.0及以上稳定版本规避版本兼容问题。
内容的提问来源于stack exchange,提问作者hieuwu
相关产品推荐
相关产品推荐

