Android Room inserts duplicate entities

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.


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