我正在使用 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)
}
关于android - 如何在 Room 中插入具有一对多关系的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67203765/