首页 > 解决方案 > 如何使用房间 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 **

标签: androidkotlin

解决方案


我找到了答案,你可以试试这个代码 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())
        })

推荐阅读