首页 > 解决方案 > Android Room 允许 Dao @Query 填充 @Ignore 列

问题描述

我希望我的 Dao 在我的 Entity 类中填充 @Ignore 列。例如:

实体

@Entity(tableName = "example")
data class Example(
    @PrimaryKey
    val id: Long,
    val value: Int
) {
    @Ignore
    var nextId: Long = 0L
}

@Dao
interface ExampleDao {
    @Query(value = "SELECT *, (id + 1) AS nextId FROM example")
    fun getAllExamples(): List<Example>
}

但是,在构建应用程序时,会产生以下警告: The query returns some columns [nextId] which are not used by com.example.app.Example并且它不会填充nextId.

是否可以在 @Query 中包含 @Ignore 列(如果是,如何)?如果没有,可以采用哪些策略将表中不存在的列填充到我的实体类中。

注意:我完全了解示例,前提是我可以简单地执行以下操作:

@Ignore
val nextId: Long = id + 1

但这不是我要问的问题的重点。

标签: androidkotlinandroid-room

解决方案


根据@CommonsWare 给我的信息,我采用的解决方案是

data class ExampleWithNextId(
    @Embedded
    val example: Example) {
    var nextId: Long = 0L
}

然后像这样在 Dao 中使用它

@Dao
interface ExampleDao {
    @Query(value = "SELECT *, (id + 1) AS nextId FROM example")
    fun getAllExamplesWithNextId(): List<ExampleWithNextId>
}

推荐阅读