如何在 Room 中插入具有一对多关系的实体 [英] How to insert entities with a one to many relationship in Room

查看:74
本文介绍了如何在 Room 中插入具有一对多关系的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Room 构建数据库,但我不知道如何将具有关系(在我的情况下为一对多)的新元素插入到数据库中.没有任何解决方案谈论过插入(他们只谈论查询数据).

I am building a database using Room and I can't figure out how to insert the new elements that have a relationship (one to many in my case) into the database. No solution has ever talked about the insertion (they only talk about querying the data).

这里是 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).您只需将各个实体插入到它们的表中即可.

There isn't a way that I am aware of that lets you directly insert a compound entity (like ShoppingListWithItems). You have to just insert the individual entities to their tables.

在您的示例中,您可能希望为您的 ShoppingList 实体定义一个插入方法,该实体返回生成的主键(以便您可以将其用于其他项目)以及为您的 ShoppingList 实体定义一个插入方法code>Item 可以插入整个列表的实体.

In your example, you would want to define an insert method for your ShoppingList entity which returns the generated primary key (so you can use it for your other items) and an insert method for your Item entities which can insert a whole list of them.

@Insert
suspend fun addNewShoppingList(newShoppingList: ShoppingList): Long

@Insert
suspend fun addNewItems(newItems: List<Item>)

然后你可以运行一个事务来批量插入它们.

Then you can run a transaction to insert them in a batch.

@Transaction
suspend fun addNewShoppingListWithItems(shoppingList: ShoppingList, items: List<Item>) {

    val listId = addNewShoppingList(shoppingList)
    
    items.forEach { it.parentListId = listId }
    addNewItems(items)
}

这篇关于如何在 Room 中插入具有一对多关系的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆