使用Room Persistance在运行时生成查询

Jac*_*ton 1 java sqlite android android-sqlite android-room

我想在运行时生成的SQLite数据库上运行查询(而不是@Dao中的标准编译时查询)。例如,我可能想在SQLite数据库中搜索一个TEXT列,以查看它是否包含N长度列表中的所有单词。在原始SQLITE中,N为3的查询如下所示:

SELECT * FROM table 
WHERE textValue LIKE %queryTerm1% 
AND textValue LIKE %queryTerm2%"
AND textValue LIKE %queryTerm3%"
Run Code Online (Sandbox Code Playgroud)

我尝试生成并传递查询的结尾,而不只是传递变量。例如 :

String generatedQuery = "textValue LIKE %queryTerm1% AND textValue LIKE %queryTerm2% AND textValue LIKE %queryTerm3%";
tableDao.find(generatedQuery);
Run Code Online (Sandbox Code Playgroud)

并在@Dao中:

@Query("SELECT * FROM tableName WHERE :endQuery")
List<POJO> find(String endQuery);
Run Code Online (Sandbox Code Playgroud)

这似乎对我不起作用。您是否知道如何使用Room运行时生成的查询?

PS:

我已经调试了Dao实现,并查看了它正在运行的语句。这确认生成的查询信息和查询已正确传递。我认为这是SQL注入预防的问题(又是SQLITE问题,而不是Room问题) 在此处输入图片说明

liv*_*ove 7

更新:Room的最新版本1.1.1现在使用SupportSQLiteQuery而不是String。

具有类型绑定的查询。最好使用此API代替r​​awQuery(String,String []),因为它允许绑定类型安全的参数。

新答案:

@Dao
     interface RawDao {
         @RawQuery(observedEntities = User.class)
         LiveData<List<User>> getUsers(SupportSQLiteQuery query);
     }
Run Code Online (Sandbox Code Playgroud)

用法:

LiveData<List<User>> liveUsers = rawDao.getUsers( new 
SimpleSQLiteQuery("SELECT * FROM User ORDER BY name DESC"));
Run Code Online (Sandbox Code Playgroud)

将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"
Run Code Online (Sandbox Code Playgroud)