SQLIntegrityConstraintViolationException

개발연습생log·2023년 1월 5일
0

Problem

목록 보기
2/4
post-thumbnail
java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (sns.comment, CONSTRAINT FKs1slvnkuemjsq2kj4h3vhx7i1 FOREIGN KEY (post_id) REFERENCES post (id))
  • 배경
    • postcomment 엔티티는 연관관계로 매핑되어 있다.
    • post는 hard delete로 구현, comment는 soft delete로 구현
    • postdelete하려고 하자 위와 같은 에러가 발생
  • 원인
    • commentpost 를 참조하고 있기 때문에 post 가 완전 삭제 되면 무결성 위반으로 위와 같은 에러가 발생
  • 해결
    • commentpost 둘다 soft delete로 구현한다.

    • Comment

      @Where(clause = "deleted_at IS NULL")
      @SQLDelete(sql = "UPDATE comment SET deleted_at = CURRENT_TIMESTAMP where id = ?")
      public class Comment extends BaseEntity {
          @Id
          @GeneratedValue(strategy = GenerationType.IDENTITY)
          private Long id;
    • Post

      @Where(clause = "deleted_at IS NULL")
      @SQLDelete(sql = "UPDATE post SET deleted_at = CURRENT_TIMESTAMP where id = ?")
      public class Post extends BaseEntity {
          @Id
          @GeneratedValue(strategy = GenerationType.IDENTITY)
          private Long id;
profile
주니어 개발자를 향해서..

0개의 댓글