Update some specific field of an entity in android Room

前端 未结 7 1618
臣服心动
臣服心动 2020-11-29 16:45

I am using android room persistence library for my new project. I want to update some field of table. I have tried like in my Dao -

// Method 1         


        
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 17:36

    As of Room 2.2.0 released October 2019, you can specify a Target Entity for updates. Then if the update parameter is different, Room will only update the partial entity columns. An example for the OP question will show this a bit more clearly.

    @Update(entity = Tour::class)
    fun update(obj: TourUpdate)
    
    @Entity
    public class TourUpdate {
        @ColumnInfo(name = "id")
        public long id;
        @ColumnInfo(name = "endAddress")
        private String endAddress;
    }
    

    Notice you have to a create a new partial entity called TourUpdate, along with your real Tour entity in the question. Now when you call update with a TourUpdate object, it will update endAddress and leave the startAddress value the same. This works perfect for me for my usecase of an insertOrUpdate method in my DAO that updates the DB with new remote values from the API but leaves the local app data in the table alone.

提交回复
热议问题