What is the difference between OnConflictStrategy.ABORT
and OnConflictStrategy.IGNORE
in Room Database?
ABORT
: roll back the transaction on conflictIGNORE
: keep the existing rowsI know both of them won't add a new row when there is an existed row.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With