首页 > 解决方案 > 如何使用 Android Room 实体仅更新某些列?

问题描述

不幸的是,@Update 注释仅具有解决冲突形式的有限功能。我的实体包含远程、不可变或本地的数据。因此,当从远程源更新实体时,我需要保留或忽略对某些列的更新。

我想构建一个从远程源获取对象的更新,并且只更新某些列。

我的实体如下所示:

@Entity
public class MyExample {
    @PrimaryKey
    public String remoteId;
    private String first;
    private String second;
    // This property is local only, don't want it reset.
    private String third;
    // constructor, getter and setter
}

这就是我现在正在做的事情:

@Query("UPDATE my_example SET first = :first, second = :second, WHERE remoteId = :remoteId")
protected abstract int updateRemote(String remoteId, String first, String second);

请注意,“第三”没有更新。

但是,每次我想添加一个新实体时,从头开始编写是非常乏味和耗时的。

我想能够做什么:

@Query("UPDATE my_example SET first = :entity.first, second = :entity.second, WHERE remoteId = :entity.remoteId")
protected abstract int updateRemote(MyExample entity);

或者

@Query("UPDATE my_example SET first, second VALUES(entity) WHERE remoteId = :entity.remoteId") protected abstract int updateRemote(MyExample entity);

或者

@Query("UPDATE my_example SET first = :entity.first, second = :entity.second, WHERE remoteId = :entity.remoteId")
protected abstract int updateRemote(MyExample entity);

或者

@Update(columns={"first", "second"})
protected abstract int updateRemote(MyExample entity);

其中任何一个都意味着我没有方法中每个参数的名称,我可以像普通@Update一样传递实体。

为了使这一点更好,将能够注释仅在@Insert 或@Update 期间设置的列。

有谁知道这样做的方法,而无需指定每个 inout 参数?

标签: androidandroid-roomandroid-architecture-components

解决方案


推荐阅读