문제상황
게시글과 댓글이 양방향 연관관계를 가지고 있는 상태에서, 댓글이 추가되어 있는 채로 게시글을 삭제를 시도했을 때 나타나는 에러이다.
org.springframework.dao.DataIntegrityViolationException: could not execute statement [Cannot delete or update a parent row: a foreign key constraint fails (`emergency_assistant`.`comments`, CONSTRAINT `FKh4c7lvsc298whoyd4w9ta25cr` FOREIGN KEY (`post_id`) REFERENCES `posts` (`post_id`))][delete from posts where post_id=?]; SQL [delete from posts where post_id=?]; constraint [null]
MySQL Workbench를 통해, DB에 직접 쿼리를 날려 삭제를 시도해도 다음과 같이 에러가 발생한다.

원인
문제상황 설명에서부터 유추가능하듯이, 게시글을 (FK로)참조하고 있는 댓글이 남아있는 상태에서 게시글을 삭제하려니 에러가 발생한 것이다. (외래키 참조 무결성 위반)
문제해결
연관관계 설정시 연관관계 노예(?)인 Post쪽에서, 어노테이션 속성을 통해 cascade 또는 orphanremoval 설정을 해주어야 한다.
class Post{
//Post가 삭제될 때 Post를 참조하는 Comment도 함께 삭제
@OneToMany(mappedBy = "post", cascade = CascadeType.All)
private final List<Comment> comments = new LinkedList<>();
}
또는
class Post{
//Post가 삭제되어, 참조하는 객체를 잃은 Comment객체들 (고아객체) 자동제거
@OneToMany(mappedBy = "post", orphanRemoval = true)
private final List<Comment> comments = new LinkedList<>();
}
양방향 연관관계를 다루며 예상치 못한 이슈가 자꾸 발생해 정리해보았다.
[TIL] 양방향 연관관계 다루기 feat.JPA
순서상 왠지 이전 글보다, 이 글을 먼저 썼어야 했을 것 같다.