我假设这不能自动完成,因此我们需要一个查询来插入父项,检索父项的 ID 并将其分配给子项的外键,然后插入子项。
第一个假设是正确的,即您必须提供父级的 id(否则如何知道父级)。
但是,您必须查询父级的第二个假设并非总是如此,在您描述的场景中也并非如此。如果在插入父对象时,如果使用便利 @Insert 作为 Long 或 Long 数组(如果插入多个父对象),则返回 id。
例如,假设你有:-
@Entity
data class Parent(
@PrimaryKey
var id: Long? = null,
var other: String
)
和
@Entity
data class Child(
@PrimaryKey
var id: Long? = null,
var parentId: Long,
var otherdata: String
)
还有一个带有@Dao 注释的类:-
@Insert
fun insert(parent: Parent): Long
@Insert
fun insert(child: Child): Long
然后您可以使用以下内容,而无需查询Parent:-
var lastParent = dao.insert(Parent(other = "Parent1 other data"))
dao.insert(Child(parentId = lastParent, otherdata = "Child1 other data"))
dao.insert(Child(parentId = lastParent, otherdata = "Child2 other data"))
// Insert a Child with it's Parent together
dao.insert(Child(
parentId = dao.insert(Parent(other = "Parent2 other data")),
otherdata = "Child3 other data"
))
- 请注意,即使您将 id 定义为 Int,插入时也会返回 Long。
- 将 Int 用于 id 是不正确的,因为 SQLite 将 id 存储为 64 位有符号整数,这对于 Int 来说太大了。
- 但是,直到 id 达到对于 Int(32 位签名)而言太大的值(即大于 2,147,483,647)时才会出现问题。