Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ;)

like image 640
Prashant Shilimkar Avatar asked Jan 09 '15 06:01

Prashant Shilimkar


People also ask

What is the difference between CascadeType remove and orphanRemoval in JPA?

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.

What is Cascade CascadeType all?

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 .

What is CascadeType remove?

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.

What does orphanRemoval true do?

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.


1 Answers

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.

like image 87
Andy Dufresne Avatar answered Sep 26 '22 14:09

Andy Dufresne