외래키 제약 조건 위반

Referential integrity constraint violation:
"FKL5MNJ9N0DI7K1V90YXNTHKC73: PUBLIC.ORDER_PRODUCT FOREIGN KEY(ORDER_ID) REFERENCES PUBLIC.ORDERS(ID)"

📌 의미:

  • ORDER_PRODUCT 테이블의 ORDER_ID가 ORDERS(ID)를 참조하고 있다.

  • 그런데 ORDERS 테이블에서 해당 ID를 먼저 삭제하려고 하자 실패한 것이다.

🔥 원인

테스트에서 @AfterEach로 다음 순서로 삭제하고 있음:

@AfterEach
void tearDown() {
    orderRepository.deleteAllInBatch();         // 💥 먼저 orders 삭제 시도
    productRepository.deleteAllInBatch();       // products
    mailSendHistoryRepository.deleteAllInBatch();
}

🔥 이 때 order_product 테이블에는 아직 order_id를 참조하는 데이터가 존재 → 외래 키 제약 위반 → 삭제 실패


✅ 해결 방법

✅ 방법 1: 삭제 순서 변경

외래 키 관계가 있는 경우는 참조하는 쪽 → 참조받는 쪽 순서로 삭제해야 함:

@AfterEach
void tearDown() {
    // 1. order_product가 먼저 삭제되도록 orderProductRepository 또는 cascade 설정
    // 2. 그 다음 orders
    orderProductRepository.deleteAllInBatch();  // ✅ 중간 테이블 먼저
    orderRepository.deleteAllInBatch();         // 그 다음 Order
    productRepository.deleteAllInBatch();
    mailSendHistoryRepository.deleteAllInBatch();
}

orderProductRepository가 없다면, Order@OneToMany(mappedBy = ..., cascade = CascadeType.ALL, orphanRemoval = true) 등으로 cascade 설정이 필요

Last updated