android - 如何使用房间 android kotlin 获取最后插入的行 ID?
问题描述
我想使用 kotlin 获取房间 android 中的最后一行 id 这是我的实体
@Entity(tableName = "tb_customer")
data class Customer(
@PrimaryKey(autoGenerate = true)
var customerId: Long = 0L,
val firstName: String,
val lastName: String,
val emailAddress: String,
val address: String,
val profileImage: String?)
我的道
@Dao
interface CustomerDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(customer: Customer): Long
@Insert
suspend fun insertPhones(customerPhones: ArrayList<CustomerPhones>)
@Delete
suspend fun delete(customer: Customer)
@Update
suspend fun update(customer: Customer)
@Query("SELECT * FROM tb_customer ORDER BY customerId ASC")
fun getAllCustomers(): LiveData<List<Customer>>
@Query("DELETE FROM tb_customer")
suspend fun clear()
}
**请帮我获取最后插入的 id **
解决方案
我找到了答案,你可以试试这个代码 Dao
@Query("SELECT customerId FROM tb_customer ORDER BY customerId DESC LIMIT 1")
fun getLastCustomer(): LiveData<Long>
a**这是存储库**
fun getLastCustomer(): LiveData<Long> {
return customerDao.getLastCustomer()
}
这是视图模型
fun getLastCustomer(): LiveData<Long> {
return repository.getLastCustomer()
}
最后从你的上下文中你必须写
customerViewModel.getLastCustomer().observe(viewLifecycleOwner,{id->
Log.d("TAG ", id.toString())
})
推荐阅读
- amazon-web-services - 将文件发布到 S3 的签名 URL
- r - 结合一些行的新数据集
- linux - 如何使用 sed 循环文件并将输出保存在不同的文件中?
- c++ - 如何从 const 字符串初始化 LPWSTR?
- javascript - 如何在“npm run build”后修复空白网页
- reactjs - 如何仅发送图像消息?(也没有发送文本)
- html - 闪亮的 html5 视频输入
- tableau-api - 工具提示更改绘图并在工具提示中显示绘图,但我只想更改绘图
- c# - Webbrowser 控件不会在不触发任何事件的情况下在屏幕上加载元素
- python - 使用 3d 数组的索引来填充 4d 数组