Search code examples
databasespring-bootjpaforeign-keysconstraints

JPA Foreign Key Restrict On Delete


Is it possible to enforce a FK constraint with only JPA annotations and not in the DB? I want to Restrict/No Action on delete to enforce that a FK reference cannot be deleted while it is being used in a parent table. However, I have not been able to accomplish this functionality without adding the FK Constraint at the DB level.

Is this possible or is it required to also add the constraint to the DB as well?

Thank you


Solution

  • Nope, it's not possible. JPA relies on the DB to enforce FK constraints.

    With Hibernate, you can provide a custom delete query using @SqlDelete. You could e.g. use a procedure to check if the constraint is going to be violated. I imagine that's not what you're looking for, though.