刷新会议室数据库中的项目

时间:2020-11-02 22:21:17

标签: android sqlite kotlin android-room

我有一个使用Room数据库将“朋友”作为帐户存储在“帐户”表中的应用程序

@Entity(tableName = "accounts")
data class Account(

    @PrimaryKey
    @ColumnInfo(name = "account_id")
    val accountId: Int,

    @ColumnInfo(name = "first_name", defaultValue = "")
    var firstname: String,

    @ColumnInfo(name = "last_name", defaultValue = "")
    var lastname: String,

    @ColumnInfo(name = "email", defaultValue = "")
    var email: String,

    @ColumnInfo(name = "status")
    var status: Int,

    @ColumnInfo(name = "role_id")
    var roleId: Int,

    @ColumnInfo(name = "lang", defaultValue = "")
    var lang: String

) : Serializable

因此,当我刷新帐户时,可能有一些

  1. 将被删除
  2. 将被插入
  3. 将被更新

识别哪些记录需要采取什么措施以及我该怎么做的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

假设您有新帐户:

val newList: List<Account> = ... //

您可以在Dao中放置以下方法:

// To delete all accounts that are not included in new list
@Query("DELETE FROM account WHERE accountId NOT IN (: newIds)")
suspend fun deleteOutdatedAccounts(newIds: List<Int>)

// To insert/update all accounts from the new list
// Thanks to OnConflictStrategy.REPLACE strategy you get both insert and update
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertUpdateAccounts(accounts: List<Account>)

// To do two methods above in single transaction
@Transaction
suspend fun refreshAccounts(newList List<Account>){
    deleteOutdatedAccounts(newList.map{it.accountId})
    insertUpdateAccounts(newList)    
}

之后,您可以从存储库或ViewModel / Presenter中调用方法refreshAccounts(newList)