Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Room database onConflict = OnConflictStrategy.REPLACE not working

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

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

like image 396
Aanal Mehta Avatar asked May 21 '19 05:05

Aanal Mehta


People also ask

What is OnConflict Onconflictstrategy replacement?

OnConflict strategy constant to replace the old data and continue the transaction. OnConflict strategy constant to rollback the transaction.

Is room database deprecated?

This method is deprecated. Gets the instance of the given Type Converter. Returns true if current thread is in a transaction. Called by Room when it is initialized.

Which element is room database responsible for query?

Room is a Database Object Mapping library that makes it easy to access database on Android applications. Rather than hiding the detail of SQLite, Room tries to embrace them by providing convenient APIs to query the database and also verify such queries at compile time.

What is Dao in room database?

When you use the Room persistence library to store your app's data, you interact with the stored data by defining data access objects, or DAOs. Each DAO includes methods that offer abstract access to your app's database. At compile time, Room automatically generates implementations of the DAOs that you define.


2 Answers

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.

like image 176
Itamar Kerbel Avatar answered Oct 16 '22 11:10

Itamar Kerbel


Have you tried to index your main column and mark it as unique?

@Index(value = {"quote"}, unique = true)}
like image 32
Hamzeh Soboh Avatar answered Oct 16 '22 12:10

Hamzeh Soboh