Android 在具有空值的实体上的文件室(SQLite)替换策略不起作用

Android 在具有空值的实体上的文件室(SQLite)替换策略不起作用,android,android-sqlite,android-room,Android,Android Sqlite,Android Room,我有实体类Person,表中不应该有多个具有相同名称和功能的人。然而,若我将人名或特征设置为null,那个么它将不起作用。如何使其与空值一起工作?请参阅下面的代码 试验 上下文=InstrumentationRegistry.getContext; AppDb db=Room.inMemoryDatabaseBuildercontext,AppDb.class.allowMainThreadQueries.build; PersonDao dao=db.PersonDao; //更换工作在这里

我有实体类Person,表中不应该有多个具有相同名称和功能的人。然而,若我将人名或特征设置为null,那个么它将不起作用。如何使其与空值一起工作?请参阅下面的代码

试验

上下文=InstrumentationRegistry.getContext; AppDb db=Room.inMemoryDatabaseBuildercontext,AppDb.class.allowMainThreadQueries.build; PersonDao dao=db.PersonDao; //更换工作在这里 插入新的人,外星人; 插入新的人,外星人; //替换在这里不起作用 dao.insertnewperContrump,空; dao.insertnewperContrump,空; //失败-实际大小=3麝香、特朗普、特朗普 assertEquals2,dao.getAll.size; Person.java

导入androidx.room.ColumnInfo; 导入androidx.room.Entity; 导入androidx.room.Index; 导入androidx.room.PrimaryKey; @EntitytableName=person,index={@Indexvalue={name,feature},unique=true} 公共阶层人士{ @ColumnInfoname=id@PrimaryKeyautoGenerate=true private int-id; @ColumnInfoname=名称私有字符串名称; @ColumnInfoname=功能私有字符串功能; 公共PersonString名称、字符串功能{ this.name=名称; 这个特征=特征; } public void setIdint id{this.id=id;} public int getId{return id;} 公共字符串getName{return name;} 公共字符串getFeature{return feature;} } PersonDao.java

导入androidx.room.Dao; 导入androidx.room.Insert; 导入androidx.room.OnConflictStrategy; 导入androidx.room.Query; 导入java.util.List; @刀 公共接口PersonDao{ @InsertonConflict=OnConflictStrategy.REPLACE 无效插入人; @QuerySelectfromPerson 列表getAll; @QuerySelectfromPersonwherefeature=:特征 列出getByFeatureString特性; } AppDb.java

导入androidx.room.Database; 导入androidx.room.RoomDatabase; @数据库 版本=1, exportSchema=false, 实体={Person.class} 公共抽象类AppDb扩展了RoomDatabase{ 公开摘要; } ,这就是为什么不会发生唯一约束冲突,因此必须进行替换

您可以将功能字段设置为@NonNull,使null不是有效值,如果为空,则可以使用默认/魔法值,如NONE

或者,如果您没有真正使用id,那么您可以将其删除,并将主键更改为“姓名”字段,以便替换具有相同姓名但不同特征的人员的插入