San*_*dip 5 android android-sqlite android-room android-architecture-components android-jetpack
我有一种情况,我想使用 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()
}
Run Code Online (Sandbox Code Playgroud)
为了获取带有图片的商店,我的实现如下:
@Transaction
@Query("SELECT * FROM store_master ORDER BY store_master.storage_id DESC")
fun loadAll(): List<StoreWithPictures>
Run Code Online (Sandbox Code Playgroud)
上述方法适用于从主表和映射表中获取数据,但我无法以相同的方式插入(即使用 @Embeded 和 @transaction 注释)。
我已经用@Transaction注释解决了这个问题。
@Transaction\nfun insertStoreWithPictures(store: Store, pictures: List<StorePicture>) {\n\n insertStore(store)\n insertPictures(pictures)\n\n}\nRun Code Online (Sandbox Code Playgroud)\n\n\n\n使用 @Transaction 注释方法可确保您在该方法中执行的所有数据库操作都将在一个事务内运行。当方法主体中抛出异常时,事务将失败。
\n