我正在使用 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
)
据我所知,没有一种方法可以让您直接插入复合实体(例如ShoppingListWithItems
)。您只需将各个实体插入到它们的表中。
在您的示例中,您需要为您的对象定义一个插入方法ShoppingList
返回生成的主键的实体(以便您可以将其用于其他项目)和插入方法Item
可以插入它们的完整列表的实体。
@Insert
suspend fun addNewShoppingList(newShoppingList: ShoppingList): Long
@Insert
suspend fun addNewItems(newItems: List<Item>)
然后您可以运行事务来批量插入它们。
@Transaction
suspend fun addNewShoppingListWithItems(shoppingList: ShoppingList, items: List<Item>) {
val listId = addNewShoppingList(shoppingList)
items.forEach { it.parentListId = listId }
addNewItems(items)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)