简体   繁体   中英

Store a list of objects without duplicates in a database DAO

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"]

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM