gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:27:53 29 4
gpt4 key购买 nike

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

@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>

上述方法适用于从主表和映射表中获取数据,但我无法以相同的方式插入(即使用@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.

关于android - 使用 Room Persistence 库插入一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51209694/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com