I have 1-N relationship (object has a list) and want remove one item from the list. What is the right way of removing item in the list with JPA?
Do I have to first update the list and merge the owner and remove the item after (if I do not remove the item and just merge the owner, orphan will remain in DB, right)? In what sequence should be merge() and remove() called, does the order of remove() and merge() matter?
Code sample:
List<Item> items = owner.getItems();
Item itemToRemove = items.get(index);
owner.remove(itemToRemove);
em.merge(owner);
em.remove(itemToRemove);
This should work in case you have orphanRemoval=true
(JPA 2.0).
For JPA 1 there is no standard way to handle this. Hibernate has @Cascade
where you can specify DELETE_ORPHAN
This is sufficient:
List<Item> items = owner.getItems(); Item itemToRemove = items.get(index); items.remove(itemToRemove);
When the EntityManager
is flushed, the link between owner
and itemToRemove
will be deleted. And if cascade
is set to CascadeType.ALL
, itemToRemove will also be deleted.
Actually, a shorter (and equivalent) version is this:
List<Item> items = owner.getItems(); // no need to keep a reference to the object that has to be removed items.remove(index);
Reference:
Thank you guys for the answers. Your answers are very similar but there are some slight differences.
Just want to make sure that I understand it right:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With