Two Laptop Bag
The moose likes Object Relational Mapping and the fly likes JPA -- Question about Updating Mappings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "JPA -- Question about Updating Mappings" Watch "JPA -- Question about Updating Mappings" New topic

JPA -- Question about Updating Mappings

Will Farquharson

Joined: Dec 02, 2008
Posts: 20


I will make an analogy of the scenario we have...

Imagine you have baskets of fruit: and, one basket having many fruit.
The BasketEntity class has a Collection<FruitEntity> (@OneToMany), and FruitEntity has a reference to BasketEntity (@ManyToOne).
The FRUIT table in the database has the "BASKET_ID" column.

In the application, the user can open a Basket and see the list of Fruit in it. He can modify the list by removing Fruit or adding some completely new Fruit via a text field.

When he clicks "Save", the Basket now needs to have the new collection of Fruit in it. Some of the fruit might be the same as before, some might be new, some might be removed.

We were under the impression we could just do basketEntity.setFruit(newCollectionOfFruit), then entityManager.merge(basketEntity). However, what this does is just adds the new fruits into the database, and doesn't remove the old ones.

We have resorted to looping over the old fruit calling entityManager.remove(aFruit) in a for loop, before we do the merge mentioned above.

Was this the correct approach to take? Is there a way we can set it up so we just have to "merge-in" the new collection and it'll disregard the old one?


James Sutherland
Ranch Hand

Joined: Oct 01, 2007
Posts: 553
You need to use orphan removal for this. Otherwise only objects explicitly deleted will be deleted.


TopLink : EclipseLink : Book:Java Persistence : Blog:Java Persistence Performance
Will Farquharson

Joined: Dec 02, 2008
Posts: 20

Thanks for the response, that's exactly the kind of thing I was looking for!

I didn't see it myself as I use JPA 1.0, but this is all the more reason to move up to JPA 2.0.
I agree. Here's the link:
subject: JPA -- Question about Updating Mappings
It's not a secret anymore!