使用 Room Persistence 库插入一对多关系

Insert One to Many Relationship using Room Persistence Library

我有一种情况,我想使用 Room 持久性库以一对多关系在 Master (store_master) 和 Mapping (store_mapping) table 中插入数据。我的实现如下:

@Entity(tableName = "store_master")
class Store {

@PrimaryKey(autoGenerate = true)
public var store_id: Int = 0

@SerializedName("name")
lateinit var store_name: String
}

@Entity(tableName = "store_mapping", foreignKeys = arrayOf(
    ForeignKey(entity = Store::class,
            parentColumns = arrayOf("store_id"),
            childColumns = arrayOf("pic_id"),
            onDelete = CASCADE)))
class StorePicture(@field:PrimaryKey(autoGenerate = true)
          @ColumnInfo(name = "id") var id: Int,
          @SerializedName("pic_id") var pic_id: Int?,
          @SerializedName("image") var storage_picture: String?)

 class StoreWithPictures {
    @Embedded
    var store: Store? = null

    @Relation(parentColumn = "store_id",
        entityColumn =  "pic_id")
    var pictures: List<StorePicture> = ArrayList()
}

为了获取带有图片的商店,我的实现如下:

@Transaction
@Query("SELECT * FROM store_master  ORDER BY store_master.storage_id DESC")
fun loadAll(): List<StoreWithPictures>

上述方法适用于从 master 和映射中获取数据 table,但我无法以相同的方式插入(即使用 @Embeded 和 @transaction 注释)。

我已经用 @Transaction 注释解决了这个问题。

 @Transaction
fun insertStoreWithPictures(store: Store, pictures: List<StorePicture>) {

    insertStore(store)
    insertPictures(pictures)

}

Annotating a method with @Transaction makes sure that all database operations you’re executing in that method will be run inside one transaction. The transaction will fail when an exception is thrown in the method body.