TL;DR: The foreign keys in your migration files and the ones in your actual database can drift apart. MySQL will even accept a
FOREIGN KEYclause and then ignore it. Without the constraint, deleting a parent row leaves orphans behind, and Hibernate then either hands you a silentnullor throws an exception that takes down the whole list. Hibernate’sddl-auto=validatewon’t notice any of it. There are two SQL queries below that will.
Foreign keys are one of those things you set up once and then forget about. The migration says book.author_id references author.id, so it does. Right?
Not necessarily. I wanted to understand what really happens when a foreign key you think exists doesn’t, so I set up a small experiment with a classic example: authors and books. I ran everything on real PostgreSQL 18 and MySQL 9.3 databases, plus a Spring Boot 3.5 app using Hibernate 6.6. All the output below is copied from those runs.
First: what a foreign key actually does for you
A foreign key is a promise the database keeps for you: “every book.author_id points at an author that exists.”
Try to break that promise and the database refuses. Here’s an attempt to delete an author who still has a book, with the foreign key in place:
PostgreSQL:
ERROR: update or delete on table "author" violates foreign key constraint "fk_book_fk_author" on table "book_fk"
DETAIL: Key (id)=(2) is still referenced from table "book_fk".
MySQL:
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails
That error is a good thing. It’s the database stopping a mistake before it becomes bad data.
Now the same delete on a book table without the foreign key:
DELETE FROM author WHERE id = 2; -- no error at all
It just works. Author 2 is gone, but two books still point at it:
id | title | author_id
----+--------------+-----------
11 | Dune | 2
13 | Dune Messiah | 2
These are orphan rows: children whose parent no longer exists. Nothing complains yet. The trouble starts when your application reads them.
How foreign keys go missing
If your migrations define the constraint, how can it be missing? More easily than you’d think. These are the ways I came across while reading up and experimenting.
1. It was never created where you think it was
Someone created a table by hand “just to test something”, a migration was marked as applied without running (both Liquibase and Flyway have ways to do that), or a database was restored from a dump taken with constraints left out. The migration file says one thing, and the database is another.
2. MySQL’s MyISAM engine silently ignores it
This one honestly surprised me. With the MyISAM engine, MySQL accepts the foreign key syntax and then does nothing with it:
CREATE TABLE book_myisam (
id BIGINT PRIMARY KEY,
author_id BIGINT,
CONSTRAINT fk_myisam_author FOREIGN KEY (author_id) REFERENCES author(id)
) ENGINE=MyISAM;
-- no error, no warning
foreign keys on book_myisam in information_schema: 0
INSERT INTO book_myisam VALUES (1, 999); -- author 999 doesn't exist... accepted
InnoDB, the default engine, does enforce foreign keys. But older tables, or tables copied from somewhere else, might still be MyISAM. It’s worth checking.
3. Foreign key checks were switched off
Imports and bulk loads often run with SET FOREIGN_KEY_CHECKS = 0 to go faster. In that mode, MySQL even lets you add a foreign key on top of data that breaks it:
SET FOREIGN_KEY_CHECKS = 0;
ALTER TABLE book ADD CONSTRAINT fk_book_author FOREIGN KEY (author_id) REFERENCES author(id);
SET FOREIGN_KEY_CHECKS = 1;
FK added with checks off; orphans still there: 2
So the constraint exists, and you still have orphans. Checking that the foreign key exists isn’t quite enough. You also want to check the data.
4. PostgreSQL’s NOT VALID
PostgreSQL has a related (and genuinely useful) feature: ADD CONSTRAINT ... NOT VALID adds the foreign key without checking existing rows:
conname | convalidated
----------------+--------------
fk_book_author | f
orphans: 2
New bad rows are blocked from that moment on:
INSERT INTO book VALUES (14, 'Children of Dune', 2);
ERROR: insert or update on table "book" violates foreign key constraint "fk_book_author"
But the old orphans stay until someone runs VALIDATE CONSTRAINT, which fails until they’re cleaned up. It’s a great tool for adding constraints to big tables safely (more on that below), but it means a foreign key can exist without being fully trusted.
What your application sees
Here’s the part that really matters day to day. A plain JPA mapping:
@Entity
class Book {
@Id Long id;
String title;
@ManyToOne
@JoinColumn(name = "author_id")
Author author;
}
Hibernate assumes the relationship is intact. When it meets an orphan, what happens depends on how the association is fetched.
Eager (the default for @ManyToOne): a silent null
findAll().size() -> 4
findById(11) (orphan) -> Dune / author=null
titles + author names -> [A Wizard of Earthsea by Ursula K. Le Guin, Dune by null,
Kindred by Octavia E. Butler, Dune Messiah by null]
No exception and no warning. Dune simply has no author. That sounds harmless, but the rest of your code doesn’t expect it. The first book.getAuthor().getName() throws a NullPointerException somewhere far away from the real cause.
Lazy: one bad row breaks the whole list
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "author_id")
Author author;
findAll().size() -> 4
titles + author names -> EntityNotFoundException: Unable to find demo.Author with id 2
Loading the books works fine, because Hibernate just puts a placeholder (a proxy) where the author should be. The moment you use the author, Hibernate tries to load it, finds nothing, and throws.
And since that usually happens while building a response for all the books, one orphan row turns the whole list into an error. The three perfectly fine books don’t get shown either. On a web page, that’s a 500 for everyone.
I got the same results on PostgreSQL and MySQL. The exact behaviour can vary between Hibernate versions and fetch strategies, so it’s worth testing yours. Either way, the root problem is the same: the data broke a promise the code relies on.
ddl-auto=validate won’t save you
Spring Boot’s spring.jpa.hibernate.ddl-auto=validate sounds like exactly the right safety net: check the schema against the entities at startup.
My demo app started without complaint:
started with ddl-auto=validate (book.author_id has NO foreign key)
Hibernate’s validation checks that tables and columns exist with compatible types. It doesn’t check foreign keys. So “the app starts” tells you nothing about whether your constraints are really there.
How to check your own database
Two queries cover most of it. Both work on PostgreSQL and MySQL.
Which foreign keys actually exist?
SELECT tc.table_name, kcu.column_name, tc.constraint_name
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu
ON kcu.constraint_name = tc.constraint_name
AND kcu.table_schema = tc.table_schema
AND kcu.table_name = tc.table_name
WHERE tc.constraint_type = 'FOREIGN KEY'
AND tc.table_schema = 'public' -- MySQL: DATABASE()
ORDER BY tc.table_name;
table_name | column_name | constraint_name
------------+-------------+-------------------
book_fk | author_id | fk_book_fk_author
In my experiment, only book_fk showed up. book.author_id was missing, which is exactly the kind of gap you want to catch. Compare this list against every @ManyToOne / @JoinColumn in your entities. Any column that should be on the list but isn’t is a candidate for orphans.
Are there orphans right now?
SELECT b.id, b.title, b.author_id
FROM book b
LEFT JOIN author a ON a.id = b.author_id
WHERE b.author_id IS NOT NULL
AND a.id IS NULL;
Read it as: “books that have an author ID, where no matching author was found.” Run one of these per relationship. It’s worth doing even where the foreign key exists, because of the FOREIGN_KEY_CHECKS and NOT VALID cases above.
Turn it into a test
The best time to find a missing foreign key is before it causes trouble. A simple integration test can run against a database built by your real migrations:
- Run the foreign key query.
- Assert that every relationship you expect, as
(table, column)pairs, is in the result. - Optionally run the orphan queries and assert they return nothing.
Now if a migration ever forgets a constraint, a test fails, instead of a page breaking months later.
Fixing it
1. Clean up the orphans first
You can’t add the constraint while orphans exist. Both databases refuse:
PostgreSQL:
ERROR: insert or update on table "book" violates foreign key constraint "fk_book_author"
DETAIL: Key (author_id)=(2) is not present in table "author".
MySQL:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails
So decide what each orphan should be. Depending on what the data means, that might be:
- Delete the child rows (if they’re meaningless without the parent).
- Set the reference to
NULL(if the column allows it and “no author” is a valid state). - Restore the missing parent (if it was deleted by mistake).
Look at the rows before you pick, and keep a backup of whatever you change.
2. Add the constraint
ALTER TABLE book
ADD CONSTRAINT fk_book_author FOREIGN KEY (author_id) REFERENCES author(id);
On a big PostgreSQL table, you can split it into two steps so normal traffic isn’t held up while existing rows are checked:
ALTER TABLE book ADD CONSTRAINT fk_book_author
FOREIGN KEY (author_id) REFERENCES author(id) NOT VALID; -- quick; protects new rows right away
ALTER TABLE book VALIDATE CONSTRAINT fk_book_author; -- checks existing rows with a lighter lock
3. Decide what deleting a parent should do
A foreign key also forces a design decision you might have skipped: what should happen to the books when an author is deleted?
ON DELETE RESTRICT(or the default,NO ACTION, which behaves almost the same): refuse the delete while books exist.ON DELETE CASCADE: delete the books too.ON DELETE SET NULL: keep the books and clear the author.
There’s no universal right answer, but making the choice on purpose is much better than finding out later what happens by accident.
The band-aid: @NotFound(IGNORE)
Hibernate has an annotation that tells it to treat a missing parent as null instead of throwing:
@ManyToOne
@NotFound(action = NotFoundAction.IGNORE)
@JoinColumn(name = "author_id")
Author author;
[A Wizard of Earthsea by Ursula K. Le Guin, Dune by null, Kindred by Octavia E. Butler, Dune Messiah by null]
The list works again. But know what you’re trading:
It forces eager loading. Hibernate even warns you at startup if you combine it with
LAZY:HHH000491: 'demo.LazyIgnoreBook.author' uses both @NotFound and FetchType.LAZY. @ManyToOne and @OneToOne associations mapped with @NotFound are forced to EAGER fetching.It hides the problem. Your data is still broken. You’ve just stopped hearing about it.
It can be a reasonable short-term fix while you clean up the data. As a permanent solution, the foreign key is far better.
The checklist
- Every
@ManyToOne/@JoinColumnhas a real foreign key in the database, so checkinformation_schema, not just the migration files - No MyISAM tables where you expect foreign keys (MySQL)
- Imports that disable
FOREIGN_KEY_CHECKSare followed by an orphan check - PostgreSQL constraints added
NOT VALIDare eventually validated - Orphan queries run (or tested) for each relationship
- An integration test fails if an expected foreign key is missing
-
ON DELETEbehaviour chosen on purpose -
@NotFound(IGNORE)used only as a temporary band-aid, if at all - Don’t rely on
ddl-auto=validateto catch missing constraints
The big lesson for me: the schema you wrote down and the schema you’re running are two different things. Foreign keys are cheap to check and expensive to miss, so it’s worth checking them.