hibernate/hibernate-orm · error · DetachedObjectException

Given entity is not associated with the persistence context

Error message

Given entity is not associated with the persistence context

What it means

Error "Given entity is not associated with the persistence context" thrown in hibernate/hibernate-orm.

Source

Thrown at hibernate-core/src/main/java/org/hibernate/event/internal/DefaultLockEventListener.java:51

		final Object instance = event.getObject();
		//noinspection ConstantValue
		if ( instance == null ) {
			throw new NullPointerException( "Attempted to lock null" );
		}

		final var lockMode = event.getLockMode();
		if ( lockMode == LockMode.WRITE || lockMode == LockMode.UPGRADE_SKIPLOCKED ) {
			throw new IllegalArgumentException( "Invalid lock mode '" + lockMode + "' passed to 'lock()'" );
		}

		final var source = event.getSession();
		final Object entity = forceInitialize( instance, source );
		//TODO: if instance was an uninitialized proxy, this is inefficient,
		//      resulting in two SQL selects

		final var entry = source.getPersistenceContextInternal().getEntry( entity );
		if ( entry == null && instance == entity ) {
			throw new DetachedObjectException( "Given entity is not associated with the persistence context" );
		}
		assert entry != null;

		upgradeLock( entity, entry, event.getLockOptions(), source );
	}
}

View on GitHub (pinned to fad1729dce)

Solutions

  1. Reattach the entity to the session (merge() or load it by id) before calling lock().
  2. Only call lock() on entities that are managed or detached-but-known to this persistence context.

When it happens

Trigger: Thrown when an operation is invoked for an entity instance that the current persistence context does not manage.

Common situations: Typical situations: passing a transient or detached object to a persistence-context operation; using an entity loaded by a different (already closed) Session; evicting the entity before the call.


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