如何用房间持久性中的新列表替换项目列表?

How to replace the list of items with new list in room persistence?

实体仅包含一个项目 ID,这也是主键,我在数据库中存储了例如 3 个项目,当列表更新时,我需要用新的 3 个项目替换现有列表新的一个。但就我而言,它添加了新的,但我需要完全替换现有的

  @Dao
public interface UserIdDao {
@Query("SELECT * FROM userIds")
Flowable<List<UserId>> allUserIds();

@Insert(onConflict = OnConflictStrategy.REPLACE)
 List<Long> update(List<UserId> ids);
}

@Entity
public class UserId{
  @PrimaryKey
  private Long id;

 @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;

UserId userId = (UserFavoriteStore) o;

return (!id.equals(userId.id));
 }
@Override


public int hashCode() {
int result = id.hashCode();
result = 31 * result + (id.hashCode());
return result;
 }}

I need to replace the existing list with new one. but in my case it adds new ones ,but I need totally replace existing ones

您编写了代码来检索 ID 和插入 ID。您没有删除 ID 的代码。

因此,向您的 DAO 添加一个 @Delete 方法来删​​除您不再需要的 ID。然后,当您想要替换 ID 时,使用 @Delete 方法删除您不再需要的 ID,并 @Insert 删除您想要的 ID。

OnConflictStrategy.REPLACE 表示 "if you try to insert a row that matches an existing row by their primary keys, do not crash, but instead replace the other columns in that existing row delete the offending rows before inserting the new ones"(参见 the SQLite docs)。在你的情况下:

  • 您没有其他列
  • 插入新 ID 不会通过主键匹配现有 ID,因为您的数据完全是主键