Home > database >  Store a list of objects without duplicates in a database DAO
Store a list of objects without duplicates in a database DAO

Time:06-06

How do I store a list of objects without duplicates in a database? I have my database DAO:

@Dao
public interface UserDAO {
    @Query("select*from User")
    List<User> getAll();
    @Insert
    void insertAll(User...users);
}

User class have:

@Entity(indices = {@Index(value = {"name"}, unique = true)})
public class User {
@ColumnInfo(name="name")
public String name;
@ColumnInfo(name="surname")
public String surname;
@PrimaryKey @NonNull
public String uid;

I recover some users from the school server and I have duplicate users and I want store some Users without duplicates in my database DAO:

Model_user.getInstance(activity.getApplicationContext()).addUser(
                                        new User(
                                                uid,
                                                name,
                                                surname));

I want store for example:["11","Jenny","McCart"],["12","Mark","McBack"] instead I store:["11","Jenny","McCart"],["12","Mark","McBack"],["11","Jenny","McCart"]

CodePudding user response:

I think for your case you've to use onConflictStrategy when inserting the code. So whenever a new entry with same uid is made, room will replace it

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAll(User...users);
  • Related