我想在运行时生成的 SQLite 数据库上运行查询(而不是 @Dao 中的标准编译时查询)。例如,我可能想在 SQLite 数据库中搜索 TEXT 列,以查看它是否包含 N 长度列表中的所有单词。在原始 SQLITE 中,N 为 3 的查询如下所示:
SELECT * FROM table
WHERE textValue LIKE %queryTerm1%
AND textValue LIKE %queryTerm2%"
AND textValue LIKE %queryTerm3%"
我已经尝试生成并传递查询的结尾,而不是仅仅传递变量。例如:
String generatedQuery = "textValue LIKE %queryTerm1% AND textValue LIKE %queryTerm2% AND textValue LIKE %queryTerm3%";
tableDao.find(generatedQuery);
在@Dao 中:
@Query("SELECT * FROM tableName WHERE :endQuery")
List<POJO> find(String endQuery);
这似乎对我不起作用。您知道如何让运行时生成的查询与 Room 一起使用吗?
附言:
我已经调试了 Dao 实现并查看了它运行的语句。这确认生成的查询信息和查询正在正确传递。我认为这是 SQL 注入(inject)预防的问题(也就是 SQLITE 问题,而不是 Room 问题)
最佳答案
更新:Room 的最新版本 1.1.1 现在使用 SupportSQLiteQuery 而不是 String。
A query with typed bindings. It is better to use this API instead of rawQuery(String, String[]) because it allows binding type safe parameters.
新答案:
@Dao
interface RawDao {
@RawQuery(observedEntities = User.class)
LiveData<List<User>> getUsers(SupportSQLiteQuery query);
}
用法:
LiveData<List<User>> liveUsers = rawDao.getUsers( new
SimpleSQLiteQuery("SELECT * FROM User ORDER BY name DESC"));
将您的 gradle 更新到 1.1.1(或任何当前版本)
implementation 'android.arch.persistence.room:runtime:1.1.1'
implementation 'android.arch.lifecycle:extensions:1.1.1'
annotationProcessor "android.arch.persistence.room:compiler:1.1.1"
关于java - 使用 Room Persistence 在运行时生成查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44637715/