Android Room onConflict = OnConflictStrategy.IGNORE无法正常工作

时间:2019-05-22 12:37:20

标签: android android-room

我正在使用Android应用程序中的会议室数据库。

在向用户插入数据时,我添加了:

 // Not working onConflict = OnConflictStrategy.IGNORE/REPLACE
    @Insert(onConflict = OnConflictStrategy.IGNORE)
        void insertUser(User users);

但是它不起作用。我还尝试了onConflictStrategy.REPLACE,但仍然无法正常工作。

用户类别(有Getter和Setter):

@Entity
public class User {

    @PrimaryKey(autoGenerate = true)
    @NonNull
    @ColumnInfo(name = "id")
    private Integer id;

    @ColumnInfo(name = "user_name")
    @NonNull
    private String name;

    @ColumnInfo(name = "email")
    private String email;

    public User(@NonNull String name, String email) {
        this.name = name;
        this.email = email;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return Objects.equals(name, user.name) &&
                Objects.equals(email, user.email);
    }

    @Override
    public int hashCode() {

        return Objects.hash(name, email);
    }
}

我也查看了其他问题并尝试了解决方案,但仍然面临问题。

1 个答案:

答案 0 :(得分:0)

您需要添加唯一索引:

@Entity(indices = {@Index(value = {"user_name", "email"}, unique = true)})
public class User {
...
}