Follow Us on Twitter

JPA Persistence Tip

by Marcel Maas on November 7, 2010 · 1 comment

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, 5.0 out of 5 based on 2 ratings
VN:F [1.9.22_1171]
Rating: 5.0/5 (2 votes cast)

{ 1 comment… read it below or add one }

JF January 30, 2011 at 12:46 am

Thank you very much,
I had noticed the same and was searching for a solution.
And it works great!



Leave a Comment


Previous post:

Next post:

About Whitehorses
Company profile

Whitehorses website

Home page

Follow us
Blog post RSS
Comment RSS