我正在处理Room数据库,并try 插入list of items条(例如,引用列表,其中包含作者姓名和我的 case 中的引用).

Following is the code I am using:

// view model
BaseApp.daoInstance?.appDao()?.insertQuotes(response!!)

// dao
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertQuotes(listData: MutableList<Quote>)

When I try to insert the same data again, it always inserts as a new data instead of replacing with the current items.

I have researched a lot for this OnConflictStrategy.REPLACE but could not find any proper answer.

Is there anyone facing the same issue and found solution or am I doing anything wrong?

Thank you in advance...!!!

推荐答案

Room, will not check and compare if you have the quote already in the DB. What it will do is look if the primary key already exists in the DB if it does, Room will replace all old data with the new one.

In your case, you are not specifying an ID so the DB is generating a unique one for you. What you should do is create a Query that will search for this quote in the DB something like this:

@Query("SELECT * from quote_table WHERE author = :author AND quote = :quote")
List<Quote> getQuoteByAuthorAndQuote(string author, string quote);

This should return a list with a single quote if one is found and empty if it does not exist.

If you would like to override the old one just update the data in the Quote POJO and insert it to the DB using Room.

Kotlin相关问答推荐

将文本与文本字段的内容对齐

如何定义一个函数来接受任何具有特定字段的数据类

Kotlin中是否可以混合使用推断和显式的通用类型参数?

Kotlin 协程按顺序执行,但仅在生产机器上执行

Kotlin - 协程未按预期执行

在 APK META-INF/library_release.kotlin_module 中复制的重复文件

找不到引用的类 kotlin.internal.annotations.AvoidUninitializedObjectCopyingCheck

有没有办法重用 Job 实例?

Kotlin 的 isNullOrBlank() 函数是否可以导入 xml 以用于数据绑定

如何在 Kotlin 中判断数组类型(不是泛型类型)

如何在 Kotlin 中创建一个打开新活动(Android Studio)的按钮?

Jetpack Compose State:修改类属性

Kotlin使用运行时断言进行空判断?

Kotlin 的 Double.toInt() 中使用了哪种方法,舍入还是截断?

使用 Kotlin 创建自定义 Dagger 2 范围

任何处理器都无法识别以下选项:'[kapt.kotlin.generated, room.incremental]'

修改扩展函数中的this

android Room 将 Null 作为非 Null 类型返回

如何使用mockk库模拟android上下文

将字符串编码为Kotlin中的UTF-8