我想复制Room数据库中现有POJO的副本。该数据库包含两个实体(人员和设备)之间的一对一关系。
Person实体包含一个主键(autogenerate = true)字段pId,它也是Device中的外键。我希望副本具有一个新的自动生成的pId,但是其他大多数列将是相同的。
我认为以下代码可能有效,但是非常麻烦,特别是如果我在Person和Device下有很多列时:
private suspend fun copyPersonWithDevice(personWithDevice: PersonWithDevice) {
withContext(Dispatchers.IO) {
val personCopy = Person()
val personCopyId = repository.insertPerson(personCopy)
val deviceCopy = Device(pId = personCopyId)
repository.insertDevice(deviceCopy)
repository.updatePerson("iterate through columns other than pId, in person entity, e.g. personWithDevice.person.name, personWithDevice.person.age, etc.")
repository.updateDevice("iterate through columns other than pId and dId, in device entity")
}
}
是否有更合乎逻辑的方式来复制POJO并将其插入数据库?
有两种通用方法-玩SQL查询(正如您所写的那样有点“麻烦”)或使用对象进行操作。
让我们看一下用例的第二种方式。假设您的“道”中有以下方法:
然后您可以尝试下一个代码:
@Transaction
private suspend fun copyPersonWithDevice(person: Person) {
withContext(Dispatchers.IO) {
val deviceForCopy = repository.getDeviceWithPersonId(person.pId)
person.pId = 0 // <- That makes Room autogenerate primary id in the next line
val personCopyId = repository.insertPerson(person) // <- new row added
if (deviceForCopy != null) {
deviceForCopy.personId = personCopyId // set foreign key with copied row's id
deviceForCopy.id = 0 // <- That makes Room autogenerate primary id in the next line
repository.insertDevice(deviceForCopy) // <- new row added
}
}
}