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

java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (exam.user_role, CONSTRAINT FKj345gk1bovqvfame88rcx7yyx FOREIGN KEY (user_id) REFERENCES users (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.

What I have tried:

I added orphanRemoval=true and CascadeType.All, but it is still not working.

Spring is completely irrelevant to your question. Its all about the MySQL database and the way you have defined the tables in your DDL.

You cannot delete a Parent row if a Child row exists on your database because of how you defined that constraint.

There is a ON DELETE .... syntax which tells MySQL what to do when a parent row is deleted, by default MySQL will reject the delete, you can change this in a number of ways, as specified in the MySQL manual, of all the odd places.

In your case as you want to NOT DELETE the Employee when you delete the Department, and you have the column

`department_id` bigint DEFAULT NULL,

defined as DEFAULT NULL then change your CONSTRAINT as below

CONSTRAINT `FKgy4qe3dnqrm3ktd76sxp7n4c2` 
        FOREIGN KEY (`department_id`) 
        REFERENCES `departments` (`id`)
    ON DELETE SET NULL
CONSTRAINT `FKgy4qe3dnqrm3ktd76sxp7n4c2` 
        FOREIGN KEY (`department_id`) 
        REFERENCES `departments` (`id`)
    ON DELETE SET DEFAULT

both would do the same thing in this case as your default is NULL for that column

You may also like...

Leave a Reply

Your email address will not be published.