[英]How to add room auto generated Primary key to another entity as a foreign key
@Entity
data class Product (
@PrimaryKey(autoGenerate = true)
var id: Long? = null
)
data class ProductList (
@Embedded var products: Product,
@Relation(
parentColumn = "id",
entityColumn = "productId",
entity = GroceryItem::class
)
var courses: List<GroceryItem?>? = null
)
@Entity
data class GroceryItem (
@PrimaryKey
var id: Int? = null,
var image: String? = null,
var price: String?= null
)
在这里,我没有任何常见的字段,所以我如何将这两个表相关联,或者如何将房间自动生成的 id 添加为外键
一个用@Insert 注释的方法可以返回一个长的。 这是为插入的行新生成的 ID。 用@Update 注释的方法可以返回一个int。 这是更新的行数。
update 将尝试使用 where 子句中的主键值更新所有字段。 如果您的实体尚未保存在数据库中,则更新查询将无法找到行并且不会更新任何内容。
您可以使用@Insert(onConflict = OnConflictStrategy.REPLACE)。 这将尝试插入实体,如果存在具有相同 ID 值的现有行,它将删除它并将其替换为您尝试插入的实体。 请注意,如果您使用自动生成的 ID,这意味着生成的行将具有与被替换的原始行不同的 ID。 如果您想保留 ID,那么您必须想出一种自定义方法来做到这一点。
所以基本上你有最近插入的项目的主键。 您可以在第二个表中插入行时使用该键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.