본문 바로가기

개발일기/프로젝트 일기

HealthDuo-java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails

위 페이지에서 삭제를 누르게 되면 

 

java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails

 

에러가 난다. 

 

mysql에서 DB 테이블이나 Row를 삭제하려고 할때 위와 같은 메시지가 발생할 때가 있다.

 

말그대로 현재 삭제하려고 하는 테이블 또는 행이 다른 곳에서 참조하고 있기 때문에 발생하는 문제다.

 

이 문제가 발생하는 이유는

 

 

댓글과 게시글이 단방향 +단방향으로 양뱡향으로 연관관계에 있다.

 

결론적으로 게시글에 댓글이 달려있으니 삭제가 안되는 것 이었다

 

따라서

 


@OneToMany(mappedBy = "bbs" )
List<Comment> comments = new ArrayList<>();

이 코드를

이렇게 

@OneToMany(mappedBy = "bbs",cascade = CascadeType.REMOVE,orphanRemoval = true )
List<Comment> comments = new ArrayList<>();

 

CascadeType.REMOVE,orphanRemoval = true를 추가해주면 

(자세한 cascadeType , orphanRomoval 내용)

 

https://zontae.tistory.com/manage/newpost/33?type=post&returnURL=https%3A%2F%2Fzontae.tistory.com%2F33

 

부모객체가 삭제될때 자식 객체가 따라서 삭제되어

 

에러가 안나게 된다.