Android Room Persistence Library: Upsert

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

    Perhaps you can make your BaseDao like this.

    secure the upsert operation with @Transaction, and try to update only if insertion is failed.

    @Dao
    public abstract class BaseDao {
        /**
        * Insert an object in the database.
        *
         * @param obj the object to be inserted.
         * @return The SQLite row id
         */
        @Insert(onConflict = OnConflictStrategy.IGNORE)
        public abstract long insert(T obj);
    
        /**
         * Insert an array of objects in the database.
         *
         * @param obj the objects to be inserted.
         * @return The SQLite row ids   
         */
        @Insert(onConflict = OnConflictStrategy.IGNORE)
        public abstract List insert(List obj);
    
        /**
         * Update an object from the database.
         *
         * @param obj the object to be updated
         */
        @Update
        public abstract void update(T obj);
    
        /**
         * Update an array of objects from the database.
         *
         * @param obj the object to be updated
         */
        @Update
        public abstract void update(List obj);
    
        /**
         * Delete an object from the database
         *
         * @param obj the object to be deleted
         */
        @Delete
        public abstract void delete(T obj);
    
        @Transaction
        public void upsert(T obj) {
            long id = insert(obj);
            if (id == -1) {
                update(obj);
            }
        }
    
        @Transaction
        public void upsert(List objList) {
            List insertResult = insert(objList);
            List updateList = new ArrayList<>();
    
            for (int i = 0; i < insertResult.size(); i++) {
                if (insertResult.get(i) == -1) {
                    updateList.add(objList.get(i));
                }
            }
    
            if (!updateList.isEmpty()) {
                update(updateList);
            }
        }
    }
    

提交回复
热议问题