如何在运行时动态查询房间数据库?

编程入门 行业动态 更新时间:2024-10-28 16:30:40
本文介绍了如何在运行时动态查询房间数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

如何在运行时动态查询房间数据库?

本文发布于:2023-06-13 09:28:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/678874.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:房间   数据库   动态   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!