【问题标题】:Android Room Allow Dao @Query to populate @Ignore columnsAndroid Room 允许 Dao @Query 填充 @Ignore 列
【发布时间】:2019-01-12 00:02:33
【问题描述】:

我希望我的 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

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

【问题讨论】:

  • “是否可以在 @Query 中包含 @Ignore 列(如果可以,如何)?” - AFAIK,不。 “如果不是,可以采用哪些策略将我的表中不存在的列填充到我的实体类中”——不要使用你的实体类。使用另一个 POJO(或 POKO,因为这是 Kotlin),它的 nextId 没有用 @Ignore 标记。因此,getAllExamples() 将返回 List&lt;SomeClassThatHasNonIgnoredNextId&gt;
  • 太可惜了,不知道以后会不会有这个功能呢?
  • 我对他们的计划一无所知。然而,我不会期待它。存在一个实体类来定义模式。用于查询结果是一件方便的事情,但它不是查询结果的要求。您要求的基本上是让他们添加 @IgnoreForSchemaButAllowForQueryResultsKThxBye 注释。
  • 这很公平,无论如何感谢您提供的信息。

标签: android kotlin android-room


【解决方案1】:

根据@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>
}

【讨论】:

    猜你喜欢
    • 2018-05-22
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 2018-04-19
    相关资源
    最近更新 更多