One of the nice things about using JPA to persist your entities to the database is the fact that you can add, update or delete child entities when calling a merge on the parent entity.
However on one of my current projects I have found that this isn’t always the case. I was trying to delete a child entity by removing it from the collection (List) and then calling merge on the parent entity. However, nothing happened. Of course I could simple delete the child enitity by explicitly calling the remove on the specific child entity, but where is the fun in that? After some digging I’ve found that the JPA provider we’ve been using (EclipseLink) doesn’t remove child entities even though I have marked the collection as “cascade all”. It does add and update child entities. This might be a nice functionality to protect less able programmers from accidentally deleting half the database when merging an entity with a nulled collection but I felt like taking a risk.
I then managed to find the eclipselink specific annotation: @PrivateOwned (org.eclipse.persistence.annotations)
This annotation tells the entity the target entity is a dependant part of the source object and is not referenced by any other object and cannot exist on its own. While using eclipselink this effectively means is that the parent entity has full control over the child entity and can also delete the entity while calling merge on the parent. Beware that by setting @PrivateOwned over a collection causes many of the operations called on to be cascaded over the relationship. So it isn’t always necessary to add a cascade annotation.
That’s all for now. This tip might just save you an hour of searching.JPA Persistence Tip,