1

我发布这个是因为 stackoverflow 上已经存在同样的问题,但没有解决方案。我正在使用 Room 库进行数据库操作。我用@Embedded@Relation用其他表创建了数据类。现在的问题是,当我在主表和连接表上放置具有多个 where 条件的连接查询时,它会返回连接表的所有/不正确数据。这表明它忽略了我在 DAO 类查询中设置的条件。重要的是,当我在外部数据库上运行相同的查询(在 chrome 中使用 stetho)时,它会按预期工作。请帮助我解决这个问题,因为这是非常关键的问题。房间版本:2.4.0

这是数据类:

data class ProductFull{
    @Embedded val product: ProductMaster,

    @Relation(
        entity = ProductZone::class,
        parentColumn = "productId",
        entityColumn = "productId",
    )
    var productZone: ProductZone? = null,
}

这是 DAO 类方法:

@Query("select * from ProductMaster as pm inner join ProductZone as pz on pz.productId = pm.productId where pz.zoneId = 3")
    abstract suspend fun getTempProducts(): List<ProductFull>

上面的查询返回 zoneId = 1 的数据类的 productZone 字段中的数据。而它应该只返回 zoneId = 3 的区域。

4

1 回答 1

1

当使用room 构建底层查询时,为查询选择的每个父级 (ProductMaster)@Relation获取所有子级 (ProductZones)。

可以在 POJO 中使用以自动获取关系实体的便捷注释。当从查询返回 POJO 时,它的所有关系也由 Room 获取https://developer.android.com/reference/kotlin/androidx/room/Relation

解决方法是两个有 2 个 dao 的一个选择父母,另一个选择所需的孩子和一个函数(使用抽象类而不是 Dao 的接口)使用第一个查询获取父母,然后为每个parent 使用第二个查询获取所需的孩子。

该函数应该用 注释@Transaction,以允许它也用注释@Query("")

你会想要这样的东西: -

@Transaction
@Query("SELECT * FROM productmaster JOIN productzone on productmaster.productId = productzone.productId WHERE productzone.zoneId = 3")
abstract fun getTempProducts(): List<ProductFull>

@Query("SELECT * FROM productzone WHERE productId=:productId AND zoneId=3")
abstract fun getTempZone(productId: Long): ProductZone

@Transaction
@Query("")
fun buildFullProducts(): List<ProductFull> {
    var rv = getTempProducts()
    for (pf: ProductFull in rv) {
        pf.productZone = getTempZone(pf.product.productId!!)
    }
    return rv
}

并使用该buildFullProducts函数检索 ProductFull 的列表

于 2021-12-25T09:50:56.647 回答