我有以下实体:
@Entity
class Foo(
@PrimaryKey
@ColumnInfo(name = "id")
val id: Long,
@ColumnInfo(name = "thing1")
val thing1: String,
@ColumnInfo(name = "thing2")
val thing2: String,
@ColumnInfo(name = "thing3")
val thing3: String,
@ColumnInfo(name = "thing4")
val thing4: String
) {
@ColumnInfo(name = "local")
var local: String? = null
}
本地是指未存储在服务器上的信息,仅在手机本地。
目前,当我从服务器提取信息时,GSON 会自动填充我的值,但由于“本地”不是来自服务器,因此不会填充到该对象中。
有没有一种方法可以在我调用更新时让 Room 跳过“本地”列的更新,而无需编写自定义更新以插入除“本地”之外的所有其他列?痛点在于我可能有很多列,并且我添加的每个新列都必须将其添加到自定义插入语句中。
我还想到了从服务器实体到新的“本地”实体的一对一映射,但是现在我必须在获得实体的任何地方处理连接语句的痛苦,因为我需要本地信息。
我希望我能做这样的事情:
@Entity
class Foo(
@PrimaryKey
@ColumnInfo(name = "id")
val id: Long,
@ColumnInfo(name = "thing1")
val instructions: String,
@ColumnInfo(name = "thing2")
val instructions: String,
@ColumnInfo(name = "thing3")
val instructions: String,
@ColumnInfo(name = "thing4")
val instructions: String
) {
@Ignore
var local: String? = null
}
使用@Ignore 注释,尝试忽略通用更新中的本地字符串。然后提供自定义更新语句,只保存本地信息
@Query("UPDATE foo SET local = :newLocal WHERE foo.id = :id")
fun updateLocal(id: Long, newLocal: String)
但是 ROOM 似乎足够聪明,可以检查我是否在本地属性上使用了 @Ignore,它不会使用该更新语句进行编译。
有什么想法吗?
最佳答案
部分更新已添加到 2.2.0
在 Dao 中,您可以执行以下操作:
// Here you specify the target entity
@Update(entity = Foo::class)
fun update(partialFoo: PartialFoo)
并沿着您的实体 Foo
创建一个包含主键和您要更新的字段的 PartialFoo
。
@Entity
class PartialFoo {
@ColumnInfo(name = "id")
val id: Long,
@ColumnInfo(name = "thing1")
val instructions: String,
}
关于android - 是否可以在 Room 中忽略基本更新中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55805587/