Qus*_*oon 8 android kotlin android-room android-jetpack
我正在使用 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)
}
Run Code Online (Sandbox Code Playgroud)
这是我的实体:
@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)
}
Run Code Online (Sandbox Code Playgroud)
据我所知,没有一种方法可以让您直接插入复合实体(例如ShoppingListWithItems)。您只需将各个实体插入到它们的表中。
在您的示例中,您需要为ShoppingList实体定义一个插入方法,该方法返回生成的主键(以便您可以将其用于其他项目),并为Item实体定义一个插入方法,该方法可以插入它们的整个列表。
@Insert
suspend fun addNewShoppingList(newShoppingList: ShoppingList): Long
Run Code Online (Sandbox Code Playgroud)
@Insert
suspend fun addNewItems(newItems: List<Item>)
Run Code Online (Sandbox Code Playgroud)
然后您可以运行事务来批量插入它们。
@Transaction
suspend fun addNewShoppingListWithItems(shoppingList: ShoppingList, items: List<Item>) {
val listId = addNewShoppingList(shoppingList)
items.forEach { it.parentListId = listId }
addNewItems(items)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5456 次 |
| 最近记录: |