Android Room Persistence Library: Upsert

前端 未结 9 643
太阳男子
太阳男子 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:32

    I could not find a SQLite query that would insert or update without causing unwanted changes to my foreign key, so instead I opted to insert first, ignoring conflicts if they occurred, and updating immediately afterwards, again ignoring conflicts.

    The insert and update methods are protected so external classes see and use the upsert method only. Keep in mind that this isn't a true upsert as if any of the MyEntity POJOS have null fields, they will overwrite what may currently be in the database. This is not a caveat for me, but it may be for your application.

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    protected abstract void insert(List entities);
    
    @Update(onConflict = OnConflictStrategy.IGNORE)
    protected abstract void update(List entities);
    
    @Transaction
    public void upsert(List entities) {
        insert(models);
        update(models);
    }
    

提交回复
热议问题