상황 : 게시글을 삭제 로직을 짤 때 댓글을 먼저 삭제해주고 게시글을 삭제하도록 했다. 이 때 벌크연산을 위해 아래와 같이 jpql로 처리했다. 그렇게 테스트를 위해 삭제 요청을 보냈는데, 외래키 참조 오류가 발생했다.

@Modifying
@Query("delete from CommentEntity c where c.post.id=?1")
void deleteCommentsByPostId(Long postId);

 

원인 :  일단 id 순으로는 댓글 다음 대댓글이 있으므로 댓글을 먼저 지우는 상황에서 발생한 거 같다.

 

해결책 : 그냥 쿼리를 두 번 날리기로 했다. 먼저 대댓글을 삭제해주고 그다음에 댓글을 삭제해주도록 했다.

@Modifying
@Query("delete from CommentEntity c where c.post.id=?1 and c.parent.id is null")
void deleteCommentsByPostId(Long postId);

@Modifying
@Query("delete from CommentEntity c where c.post.id=?1 and c.parent.id is not null")
void deleteRepliesByPostId(Long postId);

+ Recent posts