Android Room插入重复的实体 [英] Android Room inserts duplicate entities

查看:58
本文介绍了Android Room插入重复的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Android的Room库在应用程序中进行数据库交互,因此我对如何防止重复项插入数据库感到困惑.

I'm using Android's Room library for the database interaction in an application and I'm sort of stumped on how to prevent duplicate entries from being inserted into the database.

我觉得我一定很想念东西,因为这似乎应该很容易做到.我已经在Google上搜索了与该主题相关的各种单词组合,但无济于事.

I feel like I must be missing something because this seems like it should be simple to do. I've searched Google for various combinations of words relating to the subject to no avail.

我本质上是使用样本之一进行插入和查询.

I'm essentially using what one of the samples does for inserting and querying.

实体:

@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库而言,是否有什么方法可以设置何时插入数据的某些规则?我读过的一篇文章提到,自动增量ID导致每个项目在主键方面都是唯一的.如果是这样,那么使用该库的其他人又该如何考虑呢?

In terms of the Room library, is there any way to set some rules on when data should be inserted? One post I read mentioned that the auto increment ID is causing each item to be unique in terms of the primary key. If that's true, how are others using this library accounting for that?

谢谢!

推荐答案

仅在确实需要自动生成的主键时才使用它.如果您的数据具有自然主键,请使用它,并根据 REPLACE 的作用确定唯一性.

Only use an auto-generated primary key if that is really what you need as a primary key. If your data has a natural primary key, use that, and it determines the uniqueness, in terms of what REPLACE will do.

如果您想要自动生成的主键,但又希望其他某些列(或列的组合)是唯一的,请添加

If you want an auto-generated primary key, but you also want some other column (or combination of columns) to be unique, add a unique index on the column(s), and that will also affect REPLACE.

这篇关于Android Room插入重复的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆