Everyday Dev System

Cascade.REMOVE 와 orphanRemoval=true 차이 본문

내배캠 주요 학습/JPA 심화

Cascade.REMOVE 와 orphanRemoval=true 차이

chaeyoung- 2023. 7. 31. 13:01

 

 

Cascade.REMOVE

Cascade.REMOVE는

에 해당하는 부모 엔티티를 삭제할 때 그 아래에 있는 에 해당하는 자식 엔티티들이 모두 삭제되는 것이다.

 

 

 

orphanRemoval=true

위 케이스도 포함

에 해당하는 부모 엔티티의 리스트에서 요소를 삭제하면 에 해당하는 자식 엔티티가 delete 되는 기능까지 포함한다.

 

Channel 클래스 코드에 Thread 멤버필드 코드

    @OneToMany(mappedBy="channel", cascade = CascadeType.ALL, orphanRemoval=true)
    private Set<Thread> threads = new LinkedHashSet <>();

테스트 코드

    @Test
    void deleteThreadByOrphanRemovalTest() {
        // given
        var newChannel = Channel.builder().name("new-group").build();
        var newThread = Thread.builder().message("new message").build();
        var newThread2 = Thread.builder().message("new message2").build();
        newThread.setChannel(newChannel); // 채널과 스레드의 연관 관계 설정.
        newThread2.setChannel(newChannel);  // 채널과 스레드의 연관 관계 설정.
        var savedChannel = channelRepository.insertChannel(newChannel);
        var savedThread = threadRepository.insertThread(newThread);
        var savedThread2 = threadRepository.insertThread(newThread2);

        // when
        var foundChannel = channelRepository.selectChannel(savedChannel.getId());
        foundChannel.getThreads().remove(savedThread);

        // then
        //    delete
        //    from
        //        thread
        //    where
        //        id=?
    }

위와 같이 channel 객체에서 threads 요소를 삭제했을 뿐인데,

Thread 테이블에 delete 쿼리가 날라감을 알 수 있다.

 

 

즉, 고아객체 삭제는 리스트 요소로써의 영속성 전이도 해준다는 의미

 

 

영속성 전이의 가장 강력한 조합은

orphanRemoval=true  + Cascade.ALL

위와 같이 하면, 자식,부모 엔티티의 라이프 사이클이 동일해져 직접 자식 엔티티의 생명주기 관리가 가능하여, 

자식 엔티티의 Repository조차 없어도 된다.