Android Room Persistence Library: Upsert

前端 未结 9 632
太阳男子
太阳男子 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 11:40

    For more elegant way to do that I would suggest two options:

    Checking for return value from insert operation with IGNORE as a OnConflictStrategy (if it equals to -1 then it means row wasn't inserted):

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    long insert(Entity entity);
    
    @Update(onConflict = OnConflictStrategy.IGNORE)
    void update(Entity entity);
    
    @Transaction
    public void upsert(Entity entity) {
        long id = insert(entity);
        if (id == -1) {
            update(entity);   
        }
    }
    

    Handling exception from insert operation with FAIL as a OnConflictStrategy:

    @Insert(onConflict = OnConflictStrategy.FAIL)
    void insert(Entity entity);
    
    @Update(onConflict = OnConflictStrategy.FAIL)
    void update(Entity entity);
    
    @Transaction
    public void upsert(Entity entity) {
        try {
            insert(entity);
        } catch (SQLiteConstraintException exception) {
            update(entity);
        }
    }
    

提交回复
热议问题