[Querydsl][오류] Cannot delete or update a parent row: a foreign key constraint fails

2022. 7. 8. 18:52·📂 Troubleshooting & Ops
728x90
반응형

Cannot delete or update a parent row: a foreign key constraint fails를 검색해보다가 

다들 workbench에 강제적으로 삭제하라는 말 밖에 없어서 글을 작성하게 되었습니다.

 

[에러발생 문구]

1. Cannot delete or update a parent row: a foreign key constraint fails

2. ` FOREIGN KEY (`review_id`) REFERENCES `tb_debate_review` (`review_id`))

3. a foreign key constraint fails (`community`.`tb_review_member`, CONSTRAINT `FKbxh8q7ql121fkgy4cvrq1hecc` FOREIGN KEY (`review_id`) REFERENCES `tb_debate_review` (`review_id`))

 

 

1. 오류가 발생한 이유


테이블을 쿼리로 직접 삭제할 때 예외가 걸렸다. 

왜냐하면 테이블 삭제 시 관계가 되어있는 두 개 이상의 테이블의 관계가 걸려 있기 때문이다.

테이블을 참조하게 되는 불안정한 이상 상태가 되어 DBMS에서 사전에 방지를 해주는 것인데, (ORMdml cascade 지정 설정으로 삭제가 되기도 함) 이를 무시하고 강제로 삭제를 하려고 할 때 오류 메시지를 보여준다.

member(자식)테이블의 컬럼을 삭제하려고 했을때 외래키의 무결성 제약조건에 위배 되어 발생한 오류이다.

 

 

2. 해결 방법


[1. 강제적인 삭제 방법]


1. foreign key 체크 설정을 비활성화하고
2. 테이블을 삭제시킨다.
3. 테이블 삭제 후 다시 foreign key 체크를 활성화하여 안전성을 지켜주면 된다.

 

[2. 고아객체를 선언하기]

entity객체의 @onToMany에 선언하기

orphanRemoval = true

club과 members가 관계 매핑이 걸려 있어 Cannot delete or update a parent row: a foreign key constraint fails가 발생했다.

 

@OneToMany(mappedBy = "club",  orphanRemoval = true)
@JsonBackReference
private List<ClubMember> members;

주인/종의 관계는

@ManyToOne인 club이 주인이고, @OneToMany인 members가 종이다.

 

orphanRemoval = true를 종에게 선언해서 부모엔티티가 삭제되면 자식 엔티티도 삭제된다.

따라서 CascadeType.PERSIST를 함께 사용하면, 부모가 자식의 전체 생명 주기를 관리한다.

 

 

혹시 더 좋은 방법이 있다면 댓글로 피드백 부탁드리겠습니다! 감사합니다.

 

728x90
반응형
저작자표시 비영리 변경금지 (새창열림)

'📂 Troubleshooting & Ops' 카테고리의 다른 글

[AWS] 깃허브 액션 연결 후 codedeploy에서 ScriptMissing / UnknownError오류 해결 방법  (0) 2022.11.14
github action gradle.yml에러 input required and not supplied: OOO  (0) 2022.11.13
[오류해결]template might not exist or might not be accessible by any of the configured Template Resolvers  (2) 2022.07.07
[JAVA](모든 시도 해봄) / java.lang.ClassNotFoundException 오류 해결  (4) 2022.03.12
[파이어베이스]Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\ 파이어베이스 연동 오류  (0) 2021.04.29
'📂 Troubleshooting & Ops' 카테고리의 다른 글
  • [AWS] 깃허브 액션 연결 후 codedeploy에서 ScriptMissing / UnknownError오류 해결 방법
  • github action gradle.yml에러 input required and not supplied: OOO
  • [오류해결]template might not exist or might not be accessible by any of the configured Template Resolvers
  • [JAVA](모든 시도 해봄) / java.lang.ClassNotFoundException 오류 해결
foodev
foodev
이것저것 개발과 이것저것 리뷰 합니다.
    반응형
    250x250
  • foodev
    개발 개맛집
    foodev
  • 전체
    오늘
    어제
    • 분류 전체보기 (103)
      • ⭐ Featured (4)
      • 📂 Backend Engineering (36)
      • 📂 Troubleshooting & Ops (10)
      • 📂 Infra & System (7)
      • 📂 Reflections (20)
        • Year-in-Review (4)
        • Work & Career (10)
        • Lessons Learned (6)
      • 📂 Team Journal (10)
      • 📂 Archive (16)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    di란
    validation failed (numeric string is expected)
    창업패키지후기
    azure ci/cd
    해피해킹 키매핑
    서이추
    db 초기화
    nestjs pipe body
    해피해킹 카라비너
    인프라 로그 저장 비용 감소하는 방법
    db 날림
    토이프로젝트개발일지
    Azure log 비용 줄이기
    githubaction 라벨 배포
    di의존성
    db 날린 썰
    해피해킹 커스텀
    typedi 동작원리
    스냅샷과히스토리성 차이
    nestjs pipe
    typedi란
    di동작원리
    해피해킹 꿀팁
    JPA
    githubaction 라벨 ci/cd
    QueryDSL
    스냅샷과 히스토리
    Azure 로그 최소 저장 30일
    해피해킹 방향키
    개발썰
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
foodev
[Querydsl][오류] Cannot delete or update a parent row: a foreign key constraint fails
상단으로

티스토리툴바