Avoiding CascadeType.REMOVE Issues
Avoiding CascadeType.REMOVE Issues
REMOVE
The CascadeTypes REMOVE and ALL, which includes REMOVE,
provide a comfortable option to remove an entity together with all its
child entities.
But it creates several issues for to-many associations, and you should
only use it for to-one relationships.
[Link]
Why you should avoid [Link]
And it gets even worse when you specify the [Link]
on both ends of the association. Hibernate then keeps cascading the
remove operation until there are no associated entities left.
Solution
First of all, you shouldn't use the [Link] for to-many
associations. And that's also the case for [Link] which
includes the [Link].
When you don't use cascading, you need to delete the associated
entities yourself. You can either do that by calling the remove
method of the EntityManager for each entity or with a bulk
operation.
[Link]
Why you should avoid [Link]
You need to iterate through the list of associated Books and check if
it's associated with any other Author. If it's not, you call the remove
method for it. Otherwise, you just delete the association to the
Author entity.
Bulk Remove
When your association contains a lot of entities, it's better to remove
them with a few queries.
This approach is much more complicated than the one I showed you
before. But it needs a fixed number of queries and performs much
better for huge associations.
You first get the ids of all Books that Author 1 wrote alone and store
them in a List. These are the ones you need to delete in a later step.
[Link]
Why you should avoid [Link]
Then you remove all records from the association table that are
linked to Author 1. That allows you to remove Book 1 without violating
a foreign key constraint.
Now you use the List you got in step 1 and remove all Books that
Author 1 wrote alone.
And in the final step, you remove the Author entity.
// remove author
[Link](a);
[Link]