간단한 API를 직접 만들어보자(6) -댓글이 있는 카드 삭제하기-

2024. 5. 24. 11:53TIL

✔오늘 배운 중요한 🔑 point

  • @OnDelete 어노테이션은 부모 엔티티가 삭제될때 자식엔티티를 어떻게 처리할까를 지정할때 사용한다
  • @OnDelete(action= OnDeleteAction.CASCADE) 를 사용하면 부모 엔티티가 삭제될때 자식엔티티도 같이 삭제된다

🎯 오늘 배운 내용

 

댓글이 달려있는 카드 삭제시 오류 발생!!!!

댓글이 달려있는 카드를 삭제를 할려고 시도하면은 오류가 발생한다!!

 

 

org.postgresql.util.PSQLException: ERROR: update or delete on table "card" violates foreign key constraint "fkqgv5aujiclf0iihwxf4gmkf18" on table "comment"

오류 메시지에 따르면, Card 엔티티를 삭제하려고 할 때 해당 카드에 연결된 Comment 엔티티가 있어서 삭제가 실패하고 있다.

 

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="card_id",nullable=false)
@OnDelete(action= OnDeleteAction.CASCADE) // 이거 왜 작동안함?
val card: Card

분명히 @Ondelete 어노테이션으로 card 엔티티가 삭제가 되면 댓글도 같이 삭제가 되도록 구현했는데 왜 작동을 안하는걸 까?

 

SELECT
    tc.constraint_name, 
    tc.table_name, 
    kcu.column_name, 
    ccu.table_name AS foreign_table_name,
    ccu.column_name AS foreign_column_name,
    rc.update_rule,
    rc.delete_rule
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
    JOIN information_schema.referential_constraints AS rc
      ON tc.constraint_name = rc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' AND tc.table_name='comment';

 

이 쿼리는 comment 테이블에 설정된 외래 키 제약 조건을 찾아, 그 제약 조건의 상세 정보를 출력하고 이 정보에는 외래 키 제약 조건의 이름, 어떤 열이 외래 키로 설정되었는지, 외래 키가 참조하는 테이블과 열, 그리고 업데이트 및 삭제 규칙이 포함되어 있다.

 

삭제 규칙인 delete_rule이 NO ACTION으로 설정되어있는것을 확인할 수 있다.

 

 

-- 기존 외래 키 제약 조건 삭제
ALTER TABLE comment DROP CONSTRAINT fkqgv5aujiclf0iihwxf4gmkf18;

-- 새로운 외래 키 제약 조건 추가
ALTER TABLE comment
ADD CONSTRAINT fkqgv5aujiclf0iihwxf4gmkf18
FOREIGN KEY (card_id)
REFERENCES card(id)
ON DELETE CASCADE;
따라서 기존의 외래 키 제약 조건을 수정해야한다

적용후 다시 조회를 해보면

 

delete_rule이 CASCADE로 설정이 된것을 확인할 수 있다.

 

이제는 댓글이 존재하는 카드를 삭제하더라도 오류가 발생하지 않은것을 확인할 수 있다

 

CARD 테이블

 

 

COMMENT 테이블

 

🤔 어떻게 활용할까?

부모-자식 관계의 엔티티에 대해서 관리하는 방법에 대해서 알게되어 앞으로도 더 이를 활용할 수 있을것으로 보인다.

📓 오늘의 한줄

"The tragedy of life is not so much what men suffer, but rather what they miss."

- Thomas Carlyle -