Description:
|
When using a many-to-one relation mapped as cascade="all-delete-orphan", committing an update that removes children from the collection results in inconsistent behavior. I have observed the following alternatives:
- removing children through parent.getChildren().clear() on the PersistentCollection wrapper put in place during insert and then committing the change using session.update(parent) or session.merge(parent) correctly deletes the children instances from the database.
- removing children through parent.setChildren(new java.util.HashSet<>()), which removes the PersistentCollection wrapper and then committing the change using session.merge(parent) works correctly as well.
- removing children through parent.setChildren(null) and then committing the change using session.merge(parent) throws org.hibernate.HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: Parent.children
- removing children through parent.setChildren(new java.util.HashSet<>()) or parent.setChildren(null) and then committing the change using session.update(parent) removes the children from the parent's list, but fails to delete the children instances from the database.
i have attached a small readily configured maven project that displays the result of all six cases in a JUnit test case (class delteorphantest.DeleteOrphanTest in src/test/java folder) using the hibernate 4.1.3. As mentioned in the environment section, the same behavior can be observed with the older 3.6.3.Final version of hibernate as well. This example uses a Set one-to-many relation, but i tested this with a List one-to-many relation too with the same results.
|