nik*_*ers 15 java recursion orm hibernate hql
我有一个树结构,每个树Node都有父母和一个Set<Node> children.每个节点都有一个String title,我想在我选择的地方进行查询Set<String> titles,作为该节点和所有父节点的标题.我该如何写这个查询?
对单个标题的查询是这样的,但就像我说的那样,我希望它扩展到父母的整个分支.
SELECT node.title FROM Node node WHERE node.id = :id
Run Code Online (Sandbox Code Playgroud)
干杯
聂
Boz*_*zho 14
您不能使用HQL进行递归查询.看到这个.如上所述,它甚至不是标准的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
}
Run Code Online (Sandbox Code Playgroud)我绝对会选择第二种选择.
虽然无法编写您要求的递归查询,但可以使用HQL来获取层次结构; 这样做至少可以让你在内存中遍历树而不需要为每个级别访问数据库.
select n from Node n
left join fetch n.Children
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13815 次 |
| 最近记录: |