[英]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
)
Here I don't have any field as common so how can I relate this two table or how can I add room autogenerated id as a foreign key在这里,我没有任何常见的字段,所以我如何将这两个表相关联,或者如何将房间自动生成的 id 添加为外键
A method, annotated with @Insert can return a long.一个用@Insert 注释的方法可以返回一个长的。 This is the newly generated ID for the inserted row.
这是为插入的行新生成的 ID。 A method, annotated with @Update can return an int.
用@Update 注释的方法可以返回一个int。 This is the number of updated rows.
这是更新的行数。
update will try to update all your fields using the value of the primary key in a where clause. update 将尝试使用 where 子句中的主键值更新所有字段。 If your entity is not persisted in the database yet, the update query will not be able to find a row and will not update anything.
如果您的实体尚未保存在数据库中,则更新查询将无法找到行并且不会更新任何内容。
You can use @Insert(onConflict = OnConflictStrategy.REPLACE).您可以使用@Insert(onConflict = OnConflictStrategy.REPLACE)。 This will try to insert the entity and, if there is an existing row that has the same ID value, it will delete it and replace it with the entity you are trying to insert.
这将尝试插入实体,如果存在具有相同 ID 值的现有行,它将删除它并将其替换为您尝试插入的实体。 Be aware that, if you are using auto generated IDs, this means that the the resulting row will have a different ID than the original that was replaced.
请注意,如果您使用自动生成的 ID,这意味着生成的行将具有与被替换的原始行不同的 ID。 If you want to preserve the ID, then you have to come up with a custom way to do it.
如果您想保留 ID,那么您必须想出一种自定义方法来做到这一点。
So basically you have the primary key for the recently inserted Item.所以基本上你有最近插入的项目的主键。 You can use that key while inserting row in the 2nd table.
您可以在第二个表中插入行时使用该键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.