HQL递归,我该怎么做?
我有一个树结构,其中每个 Node
都有一个父级和一个 Set
String title
,我想在选择 Set
,是该节点和所有父节点的标题。我该如何编写这个查询?
对单个标题的查询是这样的,但就像我说的,我希望它扩展到整个父母分支。
SELECT node.title FROM Node node WHERE node.id = :id
干杯
尼克
I have a tree structure where each Node
has a parent and a Set<Node> children
. Each Node has a String title
, and I want to make a query where I select Set<String> titles
, being the title of this node and of all parent nodes. How do I write this query?
The query for a single title is this, but like I said, I'd like it expanded for the entire branch of parents.
SELECT node.title FROM Node node WHERE node.id = :id
Cheers
Nik
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法使用 HQL 进行递归查询。 查看此内容。正如那里所说,它甚至不是标准 SQL。您有两个选择:
进行多个查询。例如:
我肯定会选择第二个选项。
You can't do recursive queries with HQL. See this. And as stated there it is not even standard SQL. You have two options:
make multiple queries. For example:
I'd definitely go for the 2nd option.
虽然不可能编写您要求的递归查询,但可以使用 HQL 急切地获取层次结构;这样做至少可以让您在内存中遍历树,而无需访问每个级别的数据库。
While it isn't possible to write the recursive query you're asking for, it is possible to eager fetch the hierarchy with HQL; doing this would at least allow you to walk the tree in memory without hitting the database for each level.
我知道这个问题很旧,但由于它在另一个问题中链接,我想对此进行更新,如 Blaze-Persistence 为在 JPA 模型之上使用递归 CTE 提供支持。
Blaze-Persistence 是基于 JPA 的查询生成器,它支持基于 JPA 模型的许多高级 DBMS 功能。为了对 CTE 或递归 CTE 进行建模(这正是您此处所需要的),您首先需要引入一个对 CTE 结果类型进行建模的 CTE 实体。
您的示例的查询可能如下所示
这将呈现为如下所示的 SQL
您可以在文档中找到有关递归 CTE 的更多信息: https://persistence.blazebit.com/documentation/core/manual/en_US/index.html#recursive-ctes
I know this question is old, but as it was linked in a different question, I wanted to give an update on this, as Blaze-Persistence offers support for working with recursive CTEs on top of the JPA model.
Blaze-Persistence is a query builder on top of JPA which supports many of the advanced DBMS features on top of the JPA model. To model CTEs or recursive CTEs, which is what you need here, you first need to introduce a CTE entity that models the result type of the CTE.
A query for your example could look like the following
This renders to SQL looking like the following
You can find out more about recursive CTEs in the documentation: https://persistence.blazebit.com/documentation/core/manual/en_US/index.html#recursive-ctes