Android Room Persistence Library: Upsert

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

    Another approach I can think of is to get the entity via DAO by query, and then perform any desired updates. This may be less efficient compared to the other solutions in this thread in terms of runtime because of having to retrieve the full entity, but allows much more flexibility in terms of operations allowed such as on what fields/variable to update.

    For example :

    private void upsert(EntityA entityA) {
       EntityA existingEntityA = getEntityA("query1","query2");
       if (existingEntityA == null) {
          insert(entityA);
       } else {
          entityA.setParam(existingEntityA.getParam());
          update(entityA);
       }
    }
    

提交回复
热议问题