0

I'm facing an issue with Room on Android.

I have a DAO with multiple methods

    @Insert(onConflict = OnConflictStrategy.ABORT)
    suspend fun insertEntity(entity: Entity)

    @Update(onConflict = OnConflictStrategy.REPLACE)
    suspend fun updateEntity(entity: Entity)

    @Transaction
    suspend fun insertOrUpdateEntities(entities: List<Entity>) {
         entities.forEach { entity ->
            try {
                insertEntity(entity)
            } catch (sqlException: SQLiteConstraintException) {
                updateEntity(entity)
            }
    }

(I simplify the catch part, I change the object entity to do some merge of fields)

But, while the entity object in "updateEntity" is correct, the database is not update with the new values.

Do you have an idea why?

Thanks!

JohnDoe
  • 1
  • 2

1 Answers1

0

I would suggest not raising an ABORT but instead using

@Insert
suspend fun insertEntity(entity: Entity): Long

@Update
suspend fun updateEntity(entity: Entity): Int

@Transaction
suspend fun insertOrUpdateEntities(entities: List<Entity>) {
     entities.forEach { entity ->
        if (insertEntity(entity) < 1) {           
            updateEntity(entity)
        }
     }
}
  • by default @Insert has onConflictStrategy.IGNORE, so PRIMARY KEY, UNIQUE, NULL and CHECK conflicts will be ignored.
  • the @Insert method can return a long (the rowid of the inserted row, or -1 if the row was not inserted), so obtaining that can be used to determine whether or not the row was inserted.
MikeT
  • 51,415
  • 16
  • 49
  • 68