【发布时间】:2021-04-21 21:33:20
【问题描述】:
我正在使用 Room 构建数据库,但我不知道如何将具有关系的新元素(在我的例子中是一对多)插入到数据库中。没有任何解决方案谈论过插入(他们只谈论查询数据)。
这是 DAO:
@Dao
abstract class ShoppingListsDao {
@Insert
abstract suspend fun addNewShoppingList(newShoppingList: ShoppingList)
@Insert
abstract suspend fun addNewItem(newItem: Item)
// This is how I thought it would work but it didn't
@Insert
@Transaction
abstract suspend fun addNewShoppingListWithItems(newShoppingListWithItems: ShoppingListWithItems)
}
这是我的实体:
@Entity
class ShoppingList(
@PrimaryKey(autoGenerate = true)
val listID: Int,
val ListName: String
)
@Entity(foreignKeys = [ForeignKey(
entity = ShoppingList::class,
parentColumns = ["listID"],
childColumns = ["parentListID"]
)])
class Item(
@PrimaryKey(autoGenerate = true)
var itemID: Int,
val name: String,
val quantity: Int,
val parentListID: Int
)
【问题讨论】:
-
你应该正常插入它们。不需要做任何额外的事情。
-
你能解释一下吗?
-
我的意思是我要确保每个Item都有正确的parentListID,这样我才能得到每个Shopping list对应的Items。
-
您应该运行一个事务,首先插入
ShoppingList,然后插入所有Item实体。发布的答案几乎是您想要的,您遇到的问题与此问题无关,并且有大量有关插入实体列表的官方文档。 -
是的,如果你能让事情变得更清楚更好理解,请发布答案。因为我很难理解这个操作......在此先感谢您的帮助。
标签: android kotlin android-room android-jetpack