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 ;)
For the removal of ShipmentInfo, when the deletion of an OrderRequest happens, we'll use CascadeType. REMOVE. For the removal of a LineItem from an OrderRequest, we'll use orphanRemoval.
The meaning of CascadeType. ALL is that the persistence will propagate (cascade) all EntityManager operations ( PERSIST, REMOVE, REFRESH, MERGE, DETACH ) to the relating entities. It seems in your case to be a bad idea, as removing an Address would lead to removing the related User .
CascadeType. REMOVE : It means that the related entities are deleted when the owning entity is deleted. CascadeType. DETACH : It detaches all the related entities if a manual detach occurs.
If orphanRemoval is set to true, the line item entity will be deleted when the line item is removed from the order. The orphanRemoval attribute in @OneToMany and @oneToOne takes a Boolean value and is by default false.
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.
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