I have tree structures that are stored in a DB table. The table can store multiple trees. I need a query that will return all nodes in a single tree. I've used the following sites as resources but the queries in them will load all nodes for all trees into PersistenceContext (isn't that loading the entire table?). I don't want to do that, I only want to load one tree. How do I achieve that??
I am using JPA 2 with Hibernate as the provider.
OpenJPA 1.2.x select tree structure using JPQL
http://www.tikalk.com/java/load-a-tree-with-jpa-and-hibernate#comment-1821
[UPDATE] Based upon a suggestion from @bennidi, I wonder if I can use something like this:
@Entity
public class Node {
private String name;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "rootId")
private Node root;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "parentId")
private Node parent;
@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@OrderBy("name")
private List<Node> children = new LinkedList<Node>();
}
JPQL query:
select distinct n from Node n left join fetch n.children where n.rootId = ROOT_ID
I do have a question though, should I create a second table to maintain the Parent-Child relationships like in this article, or will it be fine if I just used a self-referencing table. Going with the former seems to require a bit more maintenance and probably a little more complex queries. Is it worth it? I'm not sure what problems the article is addressing.