我拥有实体类Person
,并且表中的name
和feature
不应超过一个人。但是,如果我将人员的姓名或特征设置为null,则无法使用。如何使其与空值一起使用?参见下面的代码。
测试
Context context = InstrumentationRegistry.getContext();
AppDb db = Room.inMemoryDatabaseBuilder(context, AppDb.class).allowMainThreadQueries().build();
PersonDao dao = db.personDao();
// replacement works here
dao.insert(new Person("Musk", "Alien"));
dao.insert(new Person("Musk", "Alien"));
// replacement doesn't work here
dao.insert(new Person("Trump", null));
dao.insert(new Person("Trump", null));
// fails - actual size = 3 (Musk, Trump, Trump)
assertEquals(2, dao.getAll().size());
Person.java
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Index;
import androidx.room.PrimaryKey;
@Entity(tableName = "person", indices = {@Index(value = {"name", "feature"}, unique = true)})
public class Person {
@ColumnInfo(name = "id") @PrimaryKey(autoGenerate = true) private int id;
@ColumnInfo(name = "name") private String name;
@ColumnInfo(name = "feature") private String feature;
public Person(String name, String feature) {
this.name = name;
this.feature = feature;
}
public void setId(int id) { this.id = id; }
public int getId() { return id; }
public String getName() { return name; }
public String getFeature() { return feature; }
}
PersonDao.java
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import java.util.List;
@Dao
public interface PersonDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(Person person);
@Query("SELECT * FROM person")
List<Person> getAll();
@Query("SELECT * FROM person WHERE feature = :feature")
List<Person> getByFeature(String feature);
}
AppDb.java
import androidx.room.Database;
import androidx.room.RoomDatabase;
@Database(
version = 1,
exportSchema = false,
entities = {Person.class}
)
public abstract class AppDb extends RoomDatabase {
public abstract PersonDao personDao();
}
答案 0 :(得分:1)
A null
value is unique from any other null
value,这就是为什么没有发生UNIQUE
约束冲突而必须进行替换的原因。
您可以将feature
字段设置为@NonNull
,以使null不是有效值,如果为空,则可以使用默认值/魔术值,例如"NONE"
。
或者,如果您不真正使用id
,则可以将其删除,并将PRIMARY KEY
更改为name
字段,例如,将Person
插入相同名称但不同的功能将被替换。