OK, Hibernate newbie here. This should probably be really easy, if I just knew how.
I'm modelling a hierarchy (or tree structure, if you like). Each Node has a parent Node, and a Node can have any number of child Nodes.
The database table should look like this:
Code:
ID | PARENT_ID | ...
I've written this
Node.hbm.xml:
Code:
<hibernate-mapping>
<class name="Node" table="NODE">
<id name="id" column="ID">
<generator class="native"/>
</id>
<many-to-one name="parent" class="Node" column="PARENT_ID"/>
<set name="children" inverse="true" cascade="all">
<key column="PARENT_ID" not-null="true"/>
<one-to-many class="Node"/>
</set>
</class>
</hibernate-mapping>
... and
Node.java:
Code:
public class Node {
private long id;
private Node parent;
private Collection<Node> children = new HashSet<Node>();
public Collection<Node> getChildren() {
return children;
}
public void setChildren(Collection<Node> children) {
this.children = children;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
}
Then, I run this testcase (in pseudo-code):
// Create a parentNode and save it
// Create a childNode, set childNode.parent to parentNode and save it
// Retrieve childNode from DB
// Inspect childNode.parentNode, assert that it equals parentNode
// Retrieve parentNode from DB
// Inspect parentNode.children, assert it has size == 1
This is where the testcase fails, as
parentNode.children is always empty (size == 0).
What am I doing wrong here? Any suggestions appreciated.