根据 the documentation @Insert
函数可以返回一个long
,这是插入项的新rowId
。如何使用返回值?
@Dao
interface TodoDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(todo: TodoItem): Long
}
请注意,我的 @Entity
的 id
是自动生成的。
@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
}
最佳答案
如果 id on
TodoItem 是一个
var,您可以将返回值分配给
id`,所以现在您的实体已经生成了主 key ,用于 future 的 DAO 操作。
如果您要使用@Parcelize
,请确保所有基本属性都在数据类
构造函数中。就目前而言,您的 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)
关于android - DAO:如何使用 Insert 的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59023029/