Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Room Database: Difference between OnConflictStrategy.ABORT vs IGNORE

What is the difference between OnConflictStrategy.ABORT and OnConflictStrategy.IGNORE in Room Database?

  • ABORT: roll back the transaction on conflict
  • IGNORE: keep the existing rows

I know both of them won't add a new row when there is an existed row.

  1. what is really the difference between these?
  2. In What case we must use them?
like image 551
AliSh Avatar asked Jan 20 '21 11:01

AliSh


2 Answers

A transaction usually consists of more than 1 INSERT or UPDATE statements.

Depending on your requirement you must decide what happens if any of these statements violate a UNIQUE, NOT NULL, CHECK or PRIMARY KEY constraint.

Do you want the transaction to stop when the first violation occurs and rollback the changes made by the statement that caused the violation?
If the answer is yes then you must use ABORT, which is the default behavior.

Do you want the transaction to continue with the next statement, if any of the statements violates a constraint by just ignoring and not actually executing that problematic statement?
If the answer is yes then you must use IGNORE.

like image 148
forpas Avatar answered Sep 19 '22 23:09

forpas


There is differences between ABORT and IGNORE. ABORT will cancel the transaction if you try to insert object that has same key or unique constraint and throw :

 android.database.sqlite.SQLiteConstraintException: 

while IGNORE ignore conflict, won't throw exception and return -1 as id number if your insert method is like this :

@Insert(onConflict = OnConflictStrategy.IGNORE)
 long insert(SoundCardModel soundCardModel);

instead of this :

@Insert(onConflict = OnConflictStrategy.IGNORE)
 void insert(SoundCardModel soundCardModel);

for reading :

https://developer.android.com/reference/androidx/room/OnConflictStrategy

like image 32
Eray Agdoğan Avatar answered Sep 22 '22 23:09

Eray Agdoğan