Room 有没有办法不 insert/update value if null
Room is there any way to not insert/update value if null
我最近开始使用 Room,我想知道在插入或更新实体时是否有任何方法可以检查该值是否为空,在这种情况下,不要插入/更新它。
我想做的是
@Entity
data class Person{
@PrimaryKey
val id: Int,
val name:String
val surname:String
}
是否可以通过一种简单的方式对那些不为空的字段执行@Update 操作?那些为空的保持原样?
例如,在一次更新中,我可能已经告知了 id 和姓名,但在另一次更新中,我可能已经告知了 id 和姓氏。所以我想要的是合并信息,但如果可能的话,不必进行 select 查询来检查存储的值。
我读过,但我怀疑是否可以定义一个@Entity,所有字段都定义为我之前提到的那个,然后让其他实体只需更新一些字段,例如:
@Entity(tableName = "person")
data class PersonUpdateSurname{
@PrimaryKey
val id: Int,
val name:String
}
@Entity(tableName = "person")
data class PersonUpdateSurname{
@PrimaryKey
val id: Int,
val surname:String
}
有没有办法告诉 Room 哪个是原始 table 结构?
Is there a way to tell Room which is the original table structure?
这个问题不清楚。可能你有什么误解。
尝试遵循下一个模式:
- 应该只有一个
Person
相关的数据class被注释了Room-annotations——@Entity、@PrimaryKey等等。在你的情况下是 Person
class.
- 所有其他提到的辅助 classes 应该只是 POJO(纯数据 classes),因为它们没有被持久化。在您的情况下 -
PersonName
和 PersoneSurname
(具有您描述的字段但没有 Room 的注释)。
- 在 DAO 中使用
entity
-@Update 中的参数:
@Update(entity = Person::class)
fun updateName(personName: PersonName)
@Update(entity = Person::class)
fun updateSurname(personeSurname: PersonSurname)
在你的 Repository 中调用你需要的方法。如果您只想更新姓名 - 您使用方法 updateName()
和 PersonName
class 的实例作为参数,仅更新姓氏 - 方法 updateSurname()
和 [=36 的实例=] PersonSurname
.
我最近开始使用 Room,我想知道在插入或更新实体时是否有任何方法可以检查该值是否为空,在这种情况下,不要插入/更新它。
我想做的是
@Entity
data class Person{
@PrimaryKey
val id: Int,
val name:String
val surname:String
}
是否可以通过一种简单的方式对那些不为空的字段执行@Update 操作?那些为空的保持原样?
例如,在一次更新中,我可能已经告知了 id 和姓名,但在另一次更新中,我可能已经告知了 id 和姓氏。所以我想要的是合并信息,但如果可能的话,不必进行 select 查询来检查存储的值。
我读过
@Entity(tableName = "person")
data class PersonUpdateSurname{
@PrimaryKey
val id: Int,
val name:String
}
@Entity(tableName = "person")
data class PersonUpdateSurname{
@PrimaryKey
val id: Int,
val surname:String
}
有没有办法告诉 Room 哪个是原始 table 结构?
Is there a way to tell Room which is the original table structure?
这个问题不清楚。可能你有什么误解。
尝试遵循下一个模式:
- 应该只有一个
Person
相关的数据class被注释了Room-annotations——@Entity、@PrimaryKey等等。在你的情况下是Person
class. - 所有其他提到的辅助 classes 应该只是 POJO(纯数据 classes),因为它们没有被持久化。在您的情况下 -
PersonName
和PersoneSurname
(具有您描述的字段但没有 Room 的注释)。 - 在 DAO 中使用
entity
-@Update 中的参数:
@Update(entity = Person::class)
fun updateName(personName: PersonName)
@Update(entity = Person::class)
fun updateSurname(personeSurname: PersonSurname)
在你的 Repository 中调用你需要的方法。如果您只想更新姓名 - 您使用方法 updateName()
和 PersonName
class 的实例作为参数,仅更新姓氏 - 方法 updateSurname()
和 [=36 的实例=] PersonSurname
.