房间数据库中的硬编码布尔查询 [英] Hardcode Boolean Query In Room Database
问题描述
我正在构建一个Android应用程序,该应用程序显示用户的潜在匹配项列表.用户可以单击一个来喜欢该用户,而我会将所有这些喜欢保存在本地.
I'm building an Android application that displays a list of potential matches for a user. The user can click on one to like the user, and I save all of those likes locally.
我可以编写查询以获取匹配项列表,如下所示:
I can write a query to get the list of matches like this:
@Query("SELECT * FROM match WHERE liked = :liked ORDER BY match DESC LIMIT :limit")
fun getMatches(limit: Int = 6, liked: Boolean = true): Flowable<List<Match>>
我了解到这很好用.但是,我没有预见到将liked
设置为false的任何情况,因此我很好奇是否有一种方法可以对我的布尔条件进行硬编码?如果我尝试:
I've learned that this works fine. However, I don't foresee any scenario where I'll ever set liked
to false, and so I'm curious if there is a way to hardcode my Boolean condition? If I try:
@Query("SELECT * FROM match WHERE liked = true ORDER BY match DESC LIMIT :limit")
在编译时出现以下错误:
I get the following error at compile time:
Error:(8, 0) Gradle: error: There is a problem with the query: [SQLITE_ERROR] SQL error or missing database (no such column: true)
如何在查询字符串中硬编码此布尔值?
How can I hard code this Boolean in my query string?
我也尝试过:
- 用单引号引起来的条件
-
@Query("SELECT * FROM match WHERE liked = 'true' ORDER BY match DESC LIMIT :limit")
- Wrapping the condition in single quotes
@Query("SELECT * FROM match WHERE liked = 'true' ORDER BY match DESC LIMIT :limit")
推荐答案
SQLite没有布尔数据类型. Room将其映射到
INTEGER
列,将true
映射到1
,将false
映射到0
.SQLite does not have a boolean data type. Room maps it to an
INTEGER
column, mappingtrue
to1
andfalse
to0
.所以,我希望它能起作用:
So, I would expect this to work:
@Query("SELECT * FROM match WHERE liked = 1 ORDER BY match DESC LIMIT :limit")
请记住,这种行为是无证的.但是,它不应更改—至少并非没有响亮的响尾蛇响起—因为我们需要使用迁移来处理所有更改.
Bear in mind that this behavior is undocumented. However, it shouldn't change — at least not without alarm klaxons sounding — as we'd need to use migrations to deal with any changes.
这篇关于房间数据库中的硬编码布尔查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-