如何在运行时动态查询房间数据库? [英] How to dynamically query the room database at runtime?

查看:25
本文介绍了如何在运行时动态查询房间数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在运行时构造查询?

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.

这篇关于如何在运行时动态查询房间数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆