如果待处理的@Insert具有相同的字段值,请替换数据库行

时间:2019-09-07 08:09:41

标签: android kotlin android-room

我的会议室方法addMatchUid()不遵守其OnConflictStrategy.REPLACE。它只是添加了相同的数据库行:

enter image description here

这是我的数据类:

MatchedUser.kt

@Entity(tableName = "matched_users")
data class MatchedUser(
    @PrimaryKey(autoGenerate = true) val id: Int,
    @ColumnInfo(name = "match_id") val matchId: String
)

MatchedUsersDao.kt

@Dao
interface MatchedUsersDao {

    @Query("SELECT COUNT(*) FROM matched_users WHERE :matchId = match_id LIMIT 1")
    suspend fun matchedBefore(matchId: String): Int

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun addMatchUid(match: MatchedUser)
}

正在执行addMatchId()

val match = MatchedUser(0, matchId)
CustomApplication.database?.matchedUsersDao()?.addMatchUid(match)

我对该问题的唯一猜测是,由于id不同,数据库行实际上并没有重复。如果是这种情况,当match_id为相同值时,如何确保替换行?

1 个答案:

答案 0 :(得分:0)

您可以在unique上添加match_id索引以实现所需的行为。

@Entity(tableName = "matched_users", indices = [Index(value = ["match_id"], unique = true)])
data class MatchedUser(
    @PrimaryKey(autoGenerate = true) val id: Int,
    @ColumnInfo(name = "match_id") val matchId: String
)