hibernate/hibernate-orm · error · FetchNotFoundException

Entity `%s` with identifier value `%s` does not exist

Error message

Entity `%s` with identifier value `%s` does not exist

What it means

The not-filtered branch of EntitySelectFetchInitializer.checkNotFound(): the secondary SELECT for a select-fetched to-one association found no row for the FK's id, notFoundAction == EXCEPTION (default), so FetchNotFoundException('Entity X with identifier value Y does not exist') is thrown. Same dangling-foreign-key semantics as the joined variant, but detected during the extra select performed to resolve the association.

Source

Thrown at hibernate-core/src/main/java/org/hibernate/sql/results/graph/entity/internal/EntitySelectFetchInitializer.java:306

	void checkNotFound(EntitySelectFetchInitializerData data) {
		checkNotFound( toOneMapping, affectedByFilter,
				concreteDescriptor.getEntityName(),
				data.entityIdentifier );
	}

	static void checkNotFound(
			ToOneAttributeMapping toOneMapping,
			boolean affectedByFilter,
			String entityName, Object identifier) {
		final var notFoundAction = toOneMapping.getNotFoundAction();
		if ( notFoundAction != NotFoundAction.IGNORE ) {
			if ( affectedByFilter ) {
				throw new EntityFilterException( entityName, identifier,
						toOneMapping.getNavigableRole().getFullPath() );
			}
			if ( notFoundAction == NotFoundAction.EXCEPTION ) {
				throw new FetchNotFoundException( entityName, identifier );
			}
		}
	}

	@Override
	public void initializeInstanceFromParent(Object parentInstance, Data data) {
		final var attributeMapping = getInitializedPart().asAttributeMapping();
		final Object instance =
				attributeMapping != null
						? attributeMapping.getValue( parentInstance )
						: parentInstance;
		if ( instance == null ) {
			data.setState( State.MISSING );
			data.entityIdentifier = null;
			data.setInstance( null );
		}
		else {
			data.setState( State.INITIALIZED );

View on GitHub (pinned to fad1729dce)

Solutions

  1. Repair the orphaned FKs (anti-join query to find them, then NULL or delete) and add a FOREIGN KEY constraint.
  2. If absence is acceptable, use @NotFound(action = NotFoundAction.IGNORE) or optional=true with a nullable column.
  3. Switch the association to eagerly joined and validate at load time, so problems surface with full SQL context.
  4. Point the FK at an existing row (e.g. a default/unknown placeholder entity) in systems where the reference is mandatory.

Example fix

-- find orphans before they explode at runtime
SELECT c.id, c.product_id FROM cart_item c LEFT JOIN product p ON p.id = c.product_id
WHERE c.product_id IS NOT NULL AND p.id IS NULL;

// before
@ManyToOne(fetch = FetchType.LAZY)
private Product product;

// after
@ManyToOne(fetch = FetchType.LAZY)
@NotFound(action = NotFoundAction.IGNORE)
private Product product;
Defensive patterns

Strategy: try-catch

Validate before calling

// Pre-check the FK targets the lazy association will select
String sql = "select ci.id from cart_item ci left join product p on p.id = ci.product_id "
           + "where ci.product_id is not null and p.id is null";
if (!em.createNativeQuery(sql).getResultList().isEmpty()) {
    throw new IllegalStateException("cart_item rows reference missing products");
}

Try / catch

try {
    cart.getProducts().size(); // triggers the secondary select
} catch (FetchNotFoundException e) {
    // e.getIdentifier() is the dangling product id: quarantine or repair the row
}

Prevention

When it happens

Trigger: A lazy/select-fetched @ManyToOne/@OneToOne with a non-null FK whose target row is missing; target deleted between the main query and the association select (or simply absent); database lacks FK constraints so the orphan was never prevented.

Common situations: Reference data deleted by cleanup jobs while other tables still point at it; test fixtures that insert FKs without parents; cross-service databases where another service deletes rows your schema references.

Related errors


AI-assisted analysis of hibernate/hibernate-orm@fad1729dce (2026-08-22). Data as JSON: /api/errors/0ef08fe4658e9b40. Report an issue: GitHub.