HQL递归,我该怎么做?

我有一个树结构,其中每个Node都有一个父Node和一个Set children 。 每个Node都有一个String title ,我想进行一个查询,我选择Set titles ,作为该节点和所有父节点的标题。 我该如何编写此查询?

对单个标题的查询是这样的,但就像我说的那样,我希望它扩展到父母的整个分支。

 SELECT node.title FROM Node node WHERE node.id = :id 

干杯

您不能使用HQL进行递归查询。 看到这个 。 如上所述它甚至不是标准的SQL。 你有两个选择:

  • 编写特定于供应商的递归本机SQL查询
  • 进行多次查询。 例如:

     // obtain the first node using your query while (currentNode.parent != null) { Query q = //create the query q.setParameter("id", currentNode.getParentId()); Node currentNode = (Node) q.getSingleResult(); nodes.add(currentNode); // this is the Set } 

我绝对会选择第二种选择。

虽然无法编写您要求的递归查询,但可以使用HQL来获取层次结构; 这样做至少可以让你在内存中遍历树而不需要为每个级别访问数据库。

 select n from Node n left join fetch n.Children