Reputation: 5607
I don't believe the following exists but thought it was worth the ask.
Say I have an entity Contact
with the following property:
@OneToMany(cascade = {CascadeType.ALL})
private List<Address> addresses;
Assuming an Address
is unique so it cannot belong to any other Contact
. I can obviously use cascade so that operations performed on Contact
are cascaded to Address
but is there an annotation to remove an Address
from the DB if it is removed from List<Address> addresses
.
EG. A Contact
List<Address> addresses
property contains 3 Address
values; Address#1
, Address#2
and Address#3
.
Address#3
is removed and Contact
is merged back to the DB using the entity manager. At this point Address#3
still exists in the DB but is no longer associated with anything. I have always manually dealt with this but it strikes me that its a relatively common occurrence (for me at least) and there might be an annotation that takes care of this.
Upvotes: 0
Views: 35
Reputation: 24706
Try with orphan removal option:
@OneToMany(cascade = {CascadeType.ALL}, , orphanRemoval="true")
private List<Address> addresses;
This will cause addresses to be deleted when you remove them from your list.
Upvotes: 1