android - DAO:如何使用 Insert 的返回值
问题描述
根据文档,@Insert
函数可以返回 a long
,这是rowId
插入项的新值。如何使用返回值?
@Dao
interface TodoDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(todo: TodoItem): Long
}
只是要注意id
for 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
}
解决方案
如果id on
TodoItem is a
var , you could assign the return value to
id`,那么现在你的实体有它生成的主键,用于未来的 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)
推荐阅读
- javascript - 如何在重新渲染之间为转换后的组件设置动画?
- javascript - 升级react-admin v2到v3,权限一直为空上下文不一致
- c# - 如何在 WPF 中为标签添加新字体?
- error-handling - 错误没有从 rxjava zip 函数中的 observables 冒泡
- javascript - 如何使用 koa ctx body 进行多重响应?
- windows - Windows平台C语言获取串口的DTR和RTS引脚
- delphi - Delphi 使用泛型的属性 getter 函数
- c# - c# docx 从字符串 xml 加载 xml
- vb6 - VB6 IDE中的TAB缩进?
- c - 使用指向从函数返回的结构的指针