房间数据库 onConflict = OnConflictStrategy.REPLACE 不起作用 [英] Room database onConflict = OnConflictStrategy.REPLACE not working

查看:621
本文介绍了房间数据库 onConflict = OnConflictStrategy.REPLACE 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Room 数据库并尝试插入项目列表(例如,在我的案例中包含作者姓名和引用的引用列表).

I am working on Room database and trying to insert list of items(eg. list of Quotes which contains author name and a quote in my case).

以下是我使用的代码:

// 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.

我为此OnConflictStrategy.REPLACE研究了很多,但找不到任何正确的答案.

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?

先谢谢你...!!!

推荐答案

Room,不会检查和比较数据库中是否已有报价.它会做的是查看主键是否已经存在于数据库中,如果存在,Room 将用新数据替换所有旧数据.

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.

在您的情况下,您没有指定 ID,因此 DB 会为您生成唯一的 ID.您应该做的是创建一个 Query,它将在数据库中搜索此报价,如下所示:

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.

如果您想覆盖旧的,只需更新 Quote POJO 中的数据并使用 Room 将其插入数据库.

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.

这篇关于房间数据库 onConflict = OnConflictStrategy.REPLACE 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆