Imagine you have baskets of fruit: BasketEntity.java and FruitEntity.java, 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?
Joined: Oct 01, 2007
You need to use orphan removal for this. Otherwise only objects explicitly deleted will be deleted.