Hi there,
here's a solution to a problem I was having that cost me a couple of days. I'm just sticking it here since it could help others in the future.
Basically, I have a class containing a List of children objects. This is a uni-directional one-to-many (parent/child) relationship. This simple relationship appears to be configured properly but hibernate was never persisting the children on a save of the parent. No inserts or updates were being generated.
The reason was down to the implementation of my setChildren method which basically looked like -
Code:
public void setFieldDefinitions(List fieldDefs) {
fieldDefinitions.clear();
fieldDefinitions.addAll(fieldDefs);
}
i.e. it would clear the existing List and add the newly supplied elements from the parameter List.
After going through the debugger I observed that as Hibernate processes all the properties to be persisted on an object, it takes a copy of any Collection classes. While the method doing this is called 'deepCopy' it doesn't really. It just picks up the same reference to the List belonging to my parent class.
Later, after processing, Hibernate sets the processed versions of all properties back onto the object being persisted. With my implementation of setFieldDefintions clearing the list first, this meant that the new value being set was also cleared (it's a reference to the same List). All the children were removed.
This seems a bit rude of Hibernate, but obviously the fix is easy. Re-implement setFieldDefinitions as -
Code:
public void setFieldDefinitions(List fieldDefs) {
fieldDefinitions = fieldDefs;
}
That's all. Any comments are welcomed.
Cheers,
Paul C