JPA Cascade REMOVE vs Orphan Removal

jpa 에서 비슷하게 동작하는 cascade.remove와 orphanRemoval에 대해 살펴보자.

부모 entity Category는 자식entity Product를 1:n 관계로 가지고 있다.

자식이 존재하는 상태에서 부로를 삭제시에 참조무결성 오류가 발생한다.

때문에 자식을 먼저 삭제 해야하는데.

@OneToMany에서 Cascade를 CascadeType.Remove or CascadeType.All 을 지정하면 자식 엔티티에서 자식데이터를 같이 삭제 하기때문에 
참조 무결성 오류가 생기지 않는다.

헌데. @OneToMany에 orphanRemoval도 있다. Cascade remove와 비슷하게 동작하는 것으로 보인다.
-_- 차이를 찾아보자

ref stackoverFlow

Cascading Remove

Marking a reference field with CascadeType.REMOVE (or CascadeType.ALL, which includes REMOVE) indicates that remove operations should be cascaded automatically to entity objects that are referenced by that field (multiple entity objects can be referenced by a collection field):

@Entity
class Employee {
:
@OneToOne(cascade=CascadeType.REMOVE)
private Address address;
:
}

Orphan Removal

JPA 2 supports an additional and more aggressive remove cascading mode which can be specified using the orphanRemoval element of the @OneToOne and @OneToMany annotations:

@Entity
class Employee {
:
@OneToOne(orphanRemoval=true)
private Address address;
:
}

DIFFERENCE:-

The difference between the two settings is in the response to disconnecting a relationship. For example, such as when setting the address field to null or to another Address object.

  • If orphanRemoval=true is specified the disconnected Address instance is automatically removed. This is useful for cleaning up dependent objects (e.g. Address) that should not exist without a reference from an owner object (e.g. Employee).
  • If only cascade=CascadeType.REMOVE is specified no automatic action is taken since disconnecting a relationship is not a remove
    operation.
Like what you read? Give Circlee7 a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.