Problems For To-Many Associations: Cascadetype Remove All Remove
Problems For To-Many Associations: Cascadetype Remove All Remove
Problems For To-Many Associations: Cascadetype Remove All Remove
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.
www.thoughts-on-java.org
Why you should avoid CascadeType.REMOVE
And it gets even worse when you specify the CascadeType.REMOVE
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 CascadeType.REMOVE for to-many
associations. And that's also the case for CascadeType.ALL which
includes the CascadeType.REMOVE.
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.
www.thoughts-on-java.org
Why you should avoid CascadeType.REMOVE
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.
www.thoughts-on-java.org
Why you should avoid CascadeType.REMOVE
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
em.remove(a);
www.thoughts-on-java.org