android - 可选查询参数不适用于 Room

标签 android kotlin android-room android-jetpack

假设我们有以下数据库条目:

@Entity
data class Dog(
    @ColumnInfo(name = "name") val name: String,
    @ColumnInfo(name = "breed") val breed: String?
)

如您所见,并非每只狗都定义了品种。现在我们要查询以根据品种搜索所有狗。

@Dao
interface DogDao {

    @Query("SELECT * FROM dogs WHERE breed = :breed")
    fun getByBreed(breed: String?): List<Dog>
}

有时我们想搜索具有特定品种的狗,有时我们想搜索没有定义品种的狗。问题是在第二种情况下,上面的查询将不起作用。为什么?当 getByBreed(breed:) 方法的 breed 参数为空时,Room 会将此查询转换为如下内容:

SELECT * FROM dogs WHERE breed = NULL

不幸的是,SQLite 查询空值应该是这样的:

SELECT * FROM dogs WHERE breed IS NULL

问题是,如何定义接受可选参数的查询?

最佳答案

您应该查看 SQLite 运算符。直接取自此link .

The IS and IS NOT operators work like = and != except when one or both of the operands are NULL. In this case, if both operands are NULL, then the IS operator evaluates to 1 (true) and the IS NOT operator evaluates to 0 (false). If one operand is NULL and the other is not, then the IS operator evaluates to 0 (false) and the IS NOT operator is 1 (true). It is not possible for an IS or IS NOT expression to evaluate to NULL. Operators IS and IS NOT have the same precedence as =.

所以你应该拥有并且将等同于你拥有的是:

@Dao
interface DogDao {
    @Query("SELECT * FROM dogs WHERE breed IS :breed")
    fun getByBreed(breed: String?): List<Dog>
}

关于android - 可选查询参数不适用于 Room,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58992321/

相关文章:

android - 如何在循环内动态使用带有标记的 addRule() ,在膨胀 View 时会出现异常?

kotlin - 科廷 : Is `until` and `..` just a syntax difference?

android - Kotlin + Rx : required Consumer, 找到 KFunction

android - 分页3 : "Not sure how to convert a Cursor to this method' s return type"when using PagingSource as return type in Room DAO

Android facebook 4.0.0 分享对话框不分享内容

android - 有没有办法知道设备中蓝牙芯片的详细信息?

java - RxJava 2 运算符组合,仅提供一组值中的第一个值

kotlin - 如何抑制未经检查的强制转换警告?

java - 错误 : Entities and Pojos must have a usable public constructor - Java

android - 主键不是增加房间android