Click here to Skip to main content
15,892,643 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I get this error when I try to execute this query
SQL
DELETE
FROM bookings as b
WHERE b.check_out = CURRENT_DATE;

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:

Java
@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

Java
@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;
    }

What am I doing wrong?

What I have tried:

I added orphanRemoval=true and CascadeType.All, but it is still not working.
Posted
Updated 4-Mar-22 6:22am
v2
Comments
Richard Deeming 3-Mar-22 3:37am    
At a guess, CascadeType.ALL is only applied when you delete an entity via code, and doesn't result in your database relationship having a ON DELETE CASCADE action set. When you try to delete directly via SQL, only the cascade action on the database's foreign key matters.

Check the properties of your foreign key relationship in the database.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900