Android Room Persistence Library: Upsert

前端 未结 9 615
太阳男子
太阳男子 2020-12-12 10:50

Android\'s Room persistence library graciously includes the @Insert and @Update annotations that work for objects or collections. I however have a use case (push notificatio

9条回答
  •  感情败类
    2020-12-12 11:42

    Just an update for how to do this with Kotlin retaining data of the model (Maybe to use it in a counter as in example):

    //Your Dao must be an abstract class instead of an interface (optional database constructor variable)
    @Dao
    abstract class ModelDao(val database: AppDatabase) {
    
    @Insert(onConflict = OnConflictStrategy.FAIL)
    abstract fun insertModel(model: Model)
    
    //Do a custom update retaining previous data of the model 
    //(I use constants for tables and column names)
     @Query("UPDATE $MODEL_TABLE SET $COUNT=$COUNT+1 WHERE $ID = :modelId")
     abstract fun updateModel(modelId: Long)
    
    //Declare your upsert function open
    open fun upsert(model: Model) {
        try {
           insertModel(model)
        }catch (exception: SQLiteConstraintException) {
            updateModel(model.id)
        }
    }
    }
    

    You can also use @Transaction and database constructor variable for more complex transactions using database.openHelper.writableDatabase.execSQL("SQL STATEMENT")

提交回复
热议问题