我有一种情况,我想使用 Room 持久性库以一对多关系在 Master (store_master) 和 Mapping (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 注释)。