Nested Set is a design pattern for representing hierarchies in relational databases.
The primary goal of this project is to provide reusable implementation of this pattern.
Below you can find example JPA mapping using nested set implementation. Enjoy!
@Entity
public class Tree {
@OneToMany
private Set<Node> nodes = new HashSet<>();
public NestedSet<Node> asNestedSet() {
return new NestedSet<Node>(nodes);
}
public Node getRootComponent() {
return asNestedSet().getRoot();
}
}
@Entity
public class Node implements NestedSetElement {
@ManyToOne
@JoinColumn
private Tree tree;
@Embedded
private NestedSetBound bound = new NestedSetBound();
@Override
public NestedSetBound getBound() {
return bound;
}
@Override
public void setBound(NestedSetBound bound) {
this.bound = bound;
}
public Node getParent() {
return tree.asNestedSet().getParentOf(this);
}
public final List<Node> getChildren() {
return tree.asNestedSet().getChildrenOf(this);
}
}

