What is difference between CascadeType.ALL, cascade = CascadeType.REMOVE and orphanRemoval

Prashant Shilimkar picture Prashant Shilimkar · Jan 9, 2015 · Viewed 9.8k times · Source

I searched the answer but I could not get it properly. What is difference between CascadeType.ALL, cascade = CascadeType.REMOVE, orphanRemoval when we set FetchType.EAGER on @OneToMany relationship? Once I had a problem while deleteing records. I have used following

@OneToMany(cascade = CascadeType.ALL, mappedBy = "companyEntity", fetch = FetchType.EAGER)
Set<EmployeeEntity> employeeEntities;

When I tried to delete Employee record, it was not showing me any exception and it was not deleteing record. But when I changed CascadeType.ALL to CascadeType.REMOVE then it was working. Why it was not working with CascadeType.ALL rather with CascadeType.REMOVE?

Thank you for simple explanation in advance ;)

Answer

Andy Dufresne picture Andy Dufresne · Jan 9, 2015

This explains part of your question.

'OrphanRemoval=true' Vs 'CascadeType.REMOVE'

The difference between the two settings is in the response to removing child objects from the collection pointed by parent entity.

If orphanRemoval=true is specified the removed address instance is automatically removed. If only cascade=CascadeType.REMOVE is specified no automatic action is taken since removing a relationship is not a remove operation.