我具有实体类Person
,并且我想通过feature
从数据库中查询人,该人可以为null,也可以不为null。当我将功能设置为非null时,查询有效,但当功能为null时,查询返回空列表。我在做什么错了?
测试
Context context = InstrumentationRegistry.getContext();
AppDb db = Room.inMemoryDatabaseBuilder(context, AppDb.class).allowMainThreadQueries().build();
PersonDao dao = db.personDao();
dao.insert(new Person("El Risitas", "Funny"));
dao.insert(new Person("Elon Musk", "Alien"));
dao.insert(new Person("Donald Trump", null));
assertEquals(3, dao.getAll().size());
assertEquals("Funny", dao.getByFeature("Funny").get(0).getFeature());
// fails because dao.getByFeature(null) = EMPTY LIST
assertEquals(null, dao.getByFeature(null).get(0).getFeature());
Person.java
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity(tableName = "person")
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.Query;
import java.util.List;
@Dao
public interface PersonDao {
@Insert
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 :(得分:2)
在SQL中,没有什么等于空。 (不都不等于null。)您必须使用is null
。因此您的查询可能类似于(未经测试)
SELECT * FROM person WHERE feature = :feature or (feature is null and :feature is null)