sjs
sjs

Reputation: 45

Cannot delete or update a parent row: a foreign key constraint fails Spring JPA

I have this query

     DELETE
     FROM bookings as b
     WHERE b.check_out = CURRENT_DATE;

and I get

Cannot delete or update a parent row: a foreign key constraint fails (online_booking_app.booked_rooms, CONSTRAINT FK3x1lpikb2vk75nx41lxhdicvn FOREIGN KEY (booking_id) REFERENCES bookings (id))

My Booking entity has CascadeType.ALL and mapped by matches the other side - from my research these are some of the mistakes that could lead to this message.

Here is the BookingEntity:

@Entity
@Table(name = "bookings")
public class BookingEntity extends BaseEntity {


    @OneToMany(mappedBy = "booking",cascade = CascadeType.ALL, orphanRemoval = true)
    private List<BookedRoomsEntity> bookedRooms = new ArrayList<>();

    private String firstName;
    private String lastName;
    
        public List<BookedRoomsEntity> getBookedRooms() {
        return bookedRooms;
    }

    public BookingEntity setBookedRooms(List<BookedRoomsEntity> bookedRooms) {
        this.bookedRooms = bookedRooms;
        return this;
    }

BookedRoomsEntity

@Entity
@Table(name = "booked_rooms")
public class BookedRoomsEntity extends BaseEntity {

    @ManyToOne()
    private BookingEntity booking;
    
    
        public BookingEntity getBooking() {
        return booking;
    }

    public BookedRoomsEntity setBooking(BookingEntity booking) {
        this.booking = booking;
        return this;
    }

Upvotes: 1

Views: 1208

Answers (1)

Jens Schauder
Jens Schauder

Reputation: 81907

The CascadeType does only apply to EntityManager operations.

You therefore have two options:

  • Load the entities to be deleted first and then use EntityManager.remove
  • Remove the referencing entities first with a separate JPQL statement.

Upvotes: 1

Related Questions