I have what I feel is a pretty simple scenario here that has me scratching my head. I have a one-to-many relationship between two objects:
Code:
ParentClass implements PersistentEntity, java.io.Serializable
{
...
@OneToMany(mappedBy = "parentClass",
cascade={CascadeType.ALL})
private Set<ChildClass> children = new HashSet<ChildClass>();
}
ChildClass implements PersistentEntity, java.io.Serializable
{
...
@ManyToOne(optional=false)
@JoinColumn(name="PARENT_TABLE_ID", nullable=false)
private ParentClass parentClass;
}
When using this relationship with Hibernate 3.2.1 (with Annotations and EntityManager as well) through Spring JPA 2.0.2 I get some confusing behavior. When I try to merge a detached copy of
ParentClass that contains an updated Collection of
ChildClass's (namely, I've deleted at least one of the
ChildClass's from the Collection as such (note at this point the objects are detached):
Code:
for (ChildClass removeable : parentClassInstance.getChildClasses())
{
if (removable.getSomeValue() == 1)
parentClassInstance.getChildClasses().remove(removeable);
}
// Now I want to persist this change
getPersistenceService().updateParentClass(parentClassInstance);
getPersistenceService() uses an EntityManager and the updateParentClass method looks like this:
Code:
public ParentClass updateParentClass(ParentClass pc)
{
pc = em.merge(pc);
em.flush();
return pc;
}
This code was working fine for some time. This is an active code base but it does not appear that any code that I would expect to affect this has changed in quite a while. I made a single annotation change to the Collection on ParentClass (removed the cascade), and since then this code will persist any removals of ChildClass. I've tried putting the cascade back knowing that was likely not the cause and of course it did not change anything.
NOTE: If the Collection has additions and subtractions, the additions are persisted properly, only the deletions seem to have issue.
I have several instances of this same type of logic throughout the model, all instances except this one still seems to work. I cannot reproduce this issue in a separate example to this point.
Can anyone tell me what I am missing here? I assume there is something I'm missing about how Hibernate is dealing with this internally but I can't seem to figure out what it could be.
Any crumb of assistance is greatly appreciated. I'm hoping I don't have to resort to sacrificing a rubber chicken.