JPA

[JPA] orphanRemoval

행복하개! 2020. 10. 22. 03:57

 

 

 

부모 엔티티와 연관관계가 끊어진 자식 엔티티를 자동으로 삭제해주는 기능이다.

@Entity
public class Parent {

    @Id
    @GeneratedValue
    private Long id;

    private String username;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Child> childList = new ArrayList<>();
}

orphanRemoval을 true로 하면 ,

Parent parent1 = em.find(Parent.class, parent.getId());
parent1.getChildList().remove(0); // delete 쿼리나간다.

자동으로 delete 쿼리가 나간다.

 

 

 

이 속성은 참조하는 곳이 하나일 때만 사용해야 한다. 특정 엔티티가 개인 소유할 때만 사용해야한다. 

@OneToOne과 @OneToMany에서만 사용이 가능하다.

 

 

 

CascadeType.ALL + orphanRemovel=true

이 두개를 같이 사용하게 되면 부모 엔티티가 자식의 생명주기를 모두 관리할 수 있게 된다.

'JPA' 카테고리의 다른 글

[JPA] 값 타입 Collections  (2) 2020.10.24
[JPA] 임베디드 타입  (0) 2020.10.23
[JPA] CASCADE  (0) 2020.10.22
[JPA] 지연로딩  (0) 2020.10.22
[JPA] 프록시  (0) 2020.10.22