I have a Node entity that contains a set of children Nodes within it. A child node contains a set of children, and a child of it could contain more children. There is potentially an infinite level of nesting, but in practice that would not happen.
What I want to do is count how many total children there are in the entire hierarchy starting from a given node. I'm looking for a solution that is efficient and inexpensive on the database, the app server, and memory utilization.
Here is a simplified version of the Node entity:
Code:
public class Node {
private Long id;
private String name;
private Node parent;
private Set<Node> children;
}
I've got things working for small data sets with a method like this in Node, but I'm wondering if there would be a more efficient Hibernate way of getting this data. I'm using DAOs, so I could easily put the query into it rather than asking the Node itself. I haven't tried the following with a large hierarchy yet.
Code:
public int countChildren() {
int count = 0;
Iterator<Node> nodes = children.iterator();
while (nodes.hasNext()) {
Node node = nodes.next();
count += node.countChildren();
count++;
}
return count;
}
Thanks,
Tauren
[/code]