Android Room inserts duplicate entities

半城伤御伤魂 提交于 2020-12-29 06:12:15

问题


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.

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.

The Entity:

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

The DAO:

@Dao
public interface CameraDao {

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

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

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?

Thanks!


回答1:


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.




回答2:


I stuck this situation on first application with room database. I need something to if that column data exist update other data in row else insert to table

I've one primary key and one uid(here is accountId or dvrId) that are also like primary key and should not be repeated.

For doing this you have to create indices for Entity and put all columns that you don't want replace in it like this

@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;
}

And don't forget choose REPLACE strategy

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

Now if any of id and accountId and dvrId exist in the same column data will update otherwise data will insert at new row

Hope it help



来源:https://stackoverflow.com/questions/46916388/android-room-inserts-duplicate-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!