상황 : 게시글을 삭제 로직을 짤 때 댓글을 먼저 삭제해주고 게시글을 삭제하도록 했다. 이 때 벌크연산을 위해 아래와 같이 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);
'Spring Boot' 카테고리의 다른 글
모니터링 vs 가시성(Observability) (feat. OpenTelemetry) (0) | 2024.09.14 |
---|---|
Spring Boot 페이지네이션(Page, Pageable) (0) | 2024.09.08 |
WebSocket jwt 인증 처리 (feat. filter vs interceptor) (0) | 2024.08.21 |
Spring Boot @Scheduled (0) | 2024.08.02 |
Spring Boot @PathVariable & @RequestParam (0) | 2024.07.28 |