EntityNotFoundException when loading an entity that has a missing related row
jakarta.persistence.EntityNotFoundExceptionShort answer
EntityNotFoundException means Hibernate followed an id and no row was there. Two things cause it: a foreign key column that points to a deleted or never inserted row, or a getReference proxy that is touched after its row is gone. Find the missing id first, then fix the data or the mapping.
Fix it fast
1Find out which cause you have
Read the stack trace to see which entity and which id Hibernate was loading, then look for that id in the table the association points to.
SELECT * FROM parent_table WHERE id = 42;2Match what you see, then jump to its fix
- 1
The exception appears when you load the child, not the parent, and the parent id is not in its tableA foreign key points to a row that does not existFix - 2
The exception is thrown on the first getter call, not on the getReference lineA proxy from getReference was used after its row was deletedFix - 3
After adding @NotFound the association is no longer lazy and extra queries appearUsing @NotFound changed how the association loadsFix
- 1
What does the error look like?
jakarta.persistence.EntityNotFoundExceptionConstraintViolationException on an orphaned foreign key
Cause 1 of 3
A foreign key points to a row that does not exist
1Check
Find child rows whose foreign key has no match in the parent table. This happens when the column has no real foreign key constraint, so the database never stopped the bad data.
SELECT c.id, c.parent_id
FROM child c
LEFT JOIN parent p ON p.id = c.parent_id
WHERE c.parent_id IS NOT NULL AND p.id IS NULL;2Fix
Repair the data: set the column to null or restore the parent row, then add a real foreign key so it cannot happen again. If the old data must stay as it is, map the association with @NotFound(action = NotFoundAction.IGNORE), which treats the orphan as a null reference.
UPDATE child SET parent_id = NULL
WHERE parent_id IS NOT NULL AND parent_id NOT IN (SELECT id FROM parent);
// only if the bad rows must remain
@ManyToOne
@NotFound(action = NotFoundAction.IGNORE)
private Parent parent;3Verify
Run the orphan query again; it returns no rows. Load the child entity; no exception.
./mvnw -q testConfirmed by docs.hibernate.org
Cause 2 of 3
A proxy from getReference was used after its row was deleted
1Check
getReference does not read the database. The specification says the exception is thrown when the instance state is first accessed. Look for getReference, or lazy associations, in the stack trace.
grep -rn "getReference" src/main/java2Fix
Use find when you are not sure the row exists: it returns null instead of a proxy. Check the result before use.
Parent parent = em.find(Parent.class, id);
if (parent == null) {
throw new IllegalArgumentException("Parent " + id + " not found");
}3Verify
Call the code with an id that does not exist; you get your own message and not EntityNotFoundException.
./mvnw -q testConfirmed by jakarta.ee
Cause 3 of 3
Using @NotFound changed how the association loads
1Check
Hibernate documents that this annotation makes a to-one association non-lazy. Count the queries in the SQL log.
spring.jpa.show-sql=true2Fix
Prefer fixing the data and adding a foreign key constraint, then remove @NotFound so lazy loading comes back.
ALTER TABLE child
ADD CONSTRAINT fk_child_parent FOREIGN KEY (parent_id) REFERENCES parent (id);3Verify
Inserting a child with a missing parent now fails in the database at once.
./mvnw -q testConfirmed by docs.hibernate.org
How do I stop it coming back?
- Create real foreign key constraints; do not rely on application code to keep ids valid.
- Delete through the parent with the right cascade rules, not by raw SQL on one table.
- Use find for lookups where a missing row is a normal case.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- ShopGoAn e-commerce aggregator with a Python scraping engine behind its catalog, past 10K Google Play downloads.
Related fixes
Databases
Hibernate fails on a CREATE or ALTER TABLE statement at startup
Error executing DDL "alter table events drop foreign key FKg0mkvgsqn8584qoql6a2rxheq" via JDBC Statement
Hibernate generated a CREATE, ALTER or DROP statement and MySQL refused it.
3 causes, each with a fixDatabases
MySQL Connector/J: EOFException, expected to read 4 bytes, read 0 bytes
Communications link failure
The MySQL server or something between you and it closed the connection, and the driver found out only when it tried to use it.
3 causes, each with a fixDatabases
Java cannot log in to MySQL 8: authentication plugin caching_sha2_password not supported
ERROR 2061 (HY000): Authentication plugin 'caching_sha2_password' reported error: Authentication requires secure connection.
MySQL 8 accounts use the caching_sha2_password plugin by default, and Connector/J releases before 8.0.9 cannot use it.
3 causes, each with a fixDatabases
MySQL refuses to delete a row because other rows point to it
SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails
Error 1451 means at least one child row still references the parent row you are deleting or changing.
3 causes, each with a fixDatabases
JDBC cannot talk to MySQL: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago.
Communications link failure means the TCP link to MySQL could not be opened or was closed.
3 causes, each with a fixDatabases
MySQL: could not create connection to database server
Could not create connection to database server. Attempted reconnect 3 times. Giving up.
These messages are wrappers.
3 causes, each with a fix