是否可以在运行时构造查询?
Is it possible construct a query at runtime?
@Query("SELECT * FROM playlist " + "WHERE playlist_title LIKE '% :playlistTitle %' " + "GROUP BY playlist_title " + "ORDER BY playlist_title " + "LIMIT :limit") List<IPlaylist> searchPlaylists(String playlistTitle, int limit);limit 部分是可选的.也就是说,它应该能够有限制地或没有限制地执行相同的查询.
The limit part is optional. That is, it should be able to perform the same query with or without limit.
在前一种情况下,可以进行两个有限制部分和没有限制部分的静态查询,每次都可以使用适当的查询.但有时我们可能需要处理更复杂的情况,例如构建过滤器.
In the previous case, it is possible to make two static queries with and without limit part and appropriate one can be used each time. But sometimes we may have to deal with more complex situations like building a filter.
在这种情况下,与前面的示例不同,将有多个可选部分.对于图书表,我们可能需要根据图书所属的类别、作者姓名、价格区间、出版日期等进行过滤,几乎不可能对这些部分的所有组合进行静态查询.
In that case, unlike the previous example, there will be multiple number of optional parts. For a table of books, we may need to do filtering according to the category the book belongs to, author name, price range, publication date etc. It is almost impossible to make static queries with all combinations of these parts.
推荐答案根据我的经验(简短),使用 Room 是不可能的,并不是因为 Room 限制,而是正如 @CommonsWare 隐式评论的那样,是 SQLite 的限制.您需要两个查询,因此您的 DAO 中需要两个方法.
In my experience (short) using Room that's not possible, and not because of being a Room limitation but, as implicitly commented by @CommonsWare , a limitation on SQLite. You need two queries, and therefore two methods in your DAO.
我会做类似的事情:
@Query("SELECT * FROM playlist " + "WHERE playlist_title LIKE '% :playlistTitle %' " + "GROUP BY playlist_title " + "ORDER BY playlist_title " + "LIMIT :limit") List<IPlaylist> searchPlaylists(String playlistTitle, int limit); @Query("SELECT * FROM playlist " + "WHERE playlist_title LIKE '% :playlistTitle %' " + "GROUP BY playlist_title " + "ORDER BY playlist_title ") List<IPlaylist> searchPlaylists(String playlistTitle);然后在其他地方绕过:
if (limit.isPresent()) { return playlistDao.searchPlaylists(title, limit.get()); } else { return playlistDao.searchPlaylists(title); }这是我目前能想到的最佳选择.
That 's the best option I can think at the moment.
更多推荐
如何在运行时动态查询房间数据库?
发布评论