Android Room如何制作现有POJO实体的副本并使用DAO将副本保存在数据库中

问题描述 投票:0回答:1

我想复制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并将其插入数据库?

android kotlin android-room sql-insert
1个回答
0
投票

有两种通用方法-玩SQL查询(正如您所写的那样有点“麻烦”)或使用对象进行操作。

让我们看一下用例的第二种方式。假设您的“道”中有以下方法:

  • insertPerson(person:Person):Long
  • 插入设备(设备:设备)
  • getDeviceWithPersonId(personId:String):设备? //因为有一对一的关系,所以在外键上获取设备

然后您可以尝试下一个代码:

@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  
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.