Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Databases and Redis

EntityNotFoundException when loading an entity that has a missing related row

Errorjakarta.persistence.EntityNotFoundException

Short 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.

  • Applies to Hibernate ORM 6.6, Jakarta Persistence 3.2, Java 21, MySQL 8
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 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;
  2. 2Match what you see, then jump to its fix

    1. 1The 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. 2The exception is thrown on the first getter call, not on the getReference lineA proxy from getReference was used after its row was deletedFix
    3. 3After adding @NotFound the association is no longer lazy and extra queries appearUsing @NotFound changed how the association loadsFix

What does the error look like?

  • jakarta.persistence.EntityNotFoundException
  • ConstraintViolationException 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 test

Confirmed by docs.hibernate.org

Did this fix it?

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/java

2Fix

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 test

Confirmed by jakarta.ee

Did this fix it?

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=true

2Fix

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 test

Confirmed by docs.hibernate.org

Did this fix it?

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:

Related fixes

Databases

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 fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.