Spring JPA cascade

마동찬·2023년 4월 25일
0

영속성전이(CASCADE)란 ?

부모 엔티티가 영속화될 때 자식 엔티티도 같이 영속화되고, 부모 엔티티가 삭제될 때 자식 엔티티도 삭제되는 등 특정 엔티티를 영속 상태로 만들 때 연관된 엔티티도 함께 영속 상태로 전이되는 것을 의미합니다.

public class Post extends BaseEntity {

    @Id @GeneratedValue
    @Column(name = "post_id")
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "member_id")
    private Member member;

    @Builder.Default
    @OneToMany(mappedBy = "post", cascade = CascadeType.REMOVE, orphanRemoval = true)
    private List<Comment> commentList = new ArrayList<>();

    @Builder.Default
    @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<PostImage> postImageList = new ArrayList<>();

    @Builder.Default
    @OneToMany(mappedBy = "post", cascade = CascadeType.REMOVE, orphanRemoval = true)
    private List<PostLike> postLikeList = new ArrayList<>();
  • commentList
    • comment(댓글) 의 경우 post(게시글) 가 삭제될 경우 post와 연관된 comment 가 연쇄적으로 삭제하기 위해 cascade = CascadeType.REMOVE 을 설정하였다.
  • postImageList
    • postImage(게시글 이미지)의 경우 생성, 삭제 등 라이프 사이클이 게시글에 종속적이기 때문에 cascade = CascadeType.ALL 로 설정하였다.
  • postLikeList
    • postLike(게시글 좋아요)의 경우 post(게시글)이 삭제된다면 post와 연관된 postLike 를 연쇄적으로 삭제하기 위해 cascade = CascadeType.REMOVE 을 설정하였다.

post 부터가 아닌 자식 엔티티들 부터 삭제가 되는 것일까?

부모엔티티 먼저 삭제하면 자식엔티티의 부모엔티티를 참조할 수 없기 때문이다.

따라서 자식 엔티티들의 cascade 옵션을 REMOVE 또는 ALL 로 설정할 경우 삭제하고자 하는 엔티티의 연관관계의 끝에서 부터 삭제가 된다.

ref. https://velog.io/@coconenne/%EC%8A%A4%ED%94%84%EB%A7%81-JPA-%EC%96%91%EB%B0%A9%ED%96%A5-%EC%97%B0%EA%B4%80%EA%B4%80%EA%B3%84%EC%9D%98-%EC%9D%B4%ED%95%B4-cascade

profile
새내기개발자 성장기록

0개의 댓글