Android 房间插入重复实体

Android Room inserts duplicate entities

我在应用程序中使用 Android 的 Room 库进行数据库交互,但我对如何防止将重复条目插入数据库感到困惑。

我觉得我一定是错过了什么,因为这看起来应该很简单。我搜索了 Google 与该主题相关的各种单词组合,但没有找到。

我实际上是在使用其中一个样本的插入和查询功能。

实体:

@Entity(tableName = "cameras")
public class CameraEntity {
    @PrimaryKey(autoGenerate = true)
    private int id;
    private Integer accountId;
    private Integer dvrId;
    private String vendorId;
    ...
}

DAO:

@Dao
public interface CameraDao {

    @Query("SELECT * FROM cameras")
    Flowable<List<CameraEntity>> getCameras();

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertAll(List<CameraEntity> values);
}

就Room库而言,有什么方法可以设置一些关于何时应该插入数据的规则吗?我读到的一个 post 提到自动递增 ID 导致每个项目在主键方面都是唯一的。如果这是真的,其他人如何使用这个库来解释这一点?

谢谢!

仅当您确实需要作为主键时才使用自动生成的主键。如果您的数据有一个自然主键,请使用它,它会根据 REPLACE 的作用来确定唯一性。

如果您想要一个自动生成的主键,但您还希望其他一些列(或列的组合)是唯一的,请在列上添加 a unique index,这也会影响REPLACE.

我在第一次申请房间数据库时遇到了这种情况。如果该列数据存在,我需要一些东西 update 其他行中的其他数据 insert to table

我有一个主键和一个uid(这里是accountId或dvrId)也像主键,不应该重复

为此,您必须为 Entity 创建 indices 并将所有您不想替换的列放入其中

@Entity(tableName = "cameras", indices = [Index(value = ["accountId","dvrId"], unique = true)])
public class CameraEntity {
    @PrimaryKey(autoGenerate = true)
    private int id;
    private Integer accountId;
    private Integer dvrId;
    private String vendorId;
}

别忘了选择 REPLACE 策略

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAll(List<CameraEntity> values);

现在,如果 id 和 accountId 和 dvrId 存在于同一列中,数据将更新,否则数据将插入新行

希望对您有所帮助