I have a question about object semantics and implementing parent-child relationships in Hibernate. Parent has a list of children, and Child has a reference to its parent.
The problem is: the Parent's collection of children does not actually contain the Child object; it contains a copy. When I modify the Child, the same Child in Parent's collection of children does not get updated. This defies my expectations about how Hibernate should work. Is it possible I have the mappings incorrect?
Example:
Code:
Child child = childDao.findById(id);
child.setProperty(value);
....
childDao.saveChild(child); // save child
// Get all the parent's children
List children = parent.getChildren();
The List 'children' still contains the version of child before the modification above.
Here is the mapping in Parent:
Code:
/**
* @hibernate.bag name="children" lazy="false" cascade="all"
* @hibernate.collection-key column="parent_id"
* @hibernate.collection-one-to-many
class="com.myproject.model.Child"
*/
public List getChildren() {
return this.children;
}
public void setChildren(List children) {
this.children = children;
}
In Child:
Code:
/**
* @hibernate.property column="parent_id"
* not-null="true"
*/
public int getParentId() {
return this.parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
I have tried with and without the following mapping in Child:
Code:
/**
* @hibernate.many-to-one class="com.myproject.model.Parent"
cascade="none"
* column="parent_id" update="false" insert="false"
*/
public Parent getParent() {
return this.parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
Any ideas what's wrong? Perhaps I have missed something fundamental about the way Hibernate works? I would expect Hibernate queries for the same database objects to yield equal (==) object references; is this not the case?
Thanks,
Nate