首页 > 解决方案 > DAO:如何使用 Insert 的返回值

问题描述

根据文档@Insert函数可以返回 a long,这是rowId插入项的新值。如何使用返回值?

@Dao
interface TodoDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
        fun insert(todo: TodoItem): Long
}

只是要注意idfor my@Entity是自动生成的。

@PrimaryKey(autoGenerate = true)

这是整个TodoItem实体。

@Entity(tableName = "todos")
@Parcelize
data class TodoItem(val text: String, val priority: Priority) : Parcelable {
    @PrimaryKey(autoGenerate = true)
    var todoId: Long = 0
}

标签: androiddatabasekotlinandroid-roomdao

解决方案


如果id onTodoItem is avar , you could assign the return value toid`,那么现在你的实体有它生成的主键,用于未来的 DAO 操作。


如果要使用@Parcelize,请确保所有基本属性都在data class构造函数中。就目前而言,您的todoId财产不会被放入Parcel.

@Entity(tableName = "todos")
@Parcelize
data class TodoItem(
    val text: String,
    val priority: Priority,
    @PrimaryKey(autoGenerate = true) var todoId: Long = 0
) : Parcelable

然后,给定一个名为的实体entity和一个名为 的 DAO dao

entity.todoId = dao.insert(entity)

推荐阅读