views:

255

answers:

1

Hi guys,

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

+1  A: 

You can't do recursive queries with HQL. See this. And as stated there it is not even standard SQL. You have two options:

  • write a vendor-specific recursive native SQL query
  • make multiple queries. For example:

    // 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
    }
    

I'd definitely go for the 2nd option.

Bozho
I know SQL isn't recursive, I assumed that HQL was designed with overcoming this limitation in mind.
niklassaers
I'd go for Bozho's second solution too, if the tree is not too deep or complex. But say your tree is ten "queries" deep or you have many nodes, for which you want to get this full title, you might end up with a lot of queries and a performance problem. One way to solve that, depending on your situation, is to write the full title to the db on saving the record, thus saving time when retrieving.
asgerhallas
That is indeed my problem, the tree can be very deep, which is why I'd like Hibernate to take care of optimizing how to interact with the database. I was hoping for it know smart solutions and possibly lead to a database transition into one that can handle such issues.
niklassaers
I think the answer thus is: HQL has no recursion, use other optimization strategies. The one I'm going for is "materialized paths". Thank you very much for your help :-)
niklassaers