hibernate/hibernate-orm · error · IllegalArgumentException

Given entity is not associated with the persistence context

Error message

Given entity is not associated with the persistence context

What it means

DefaultDeleteEventListener can delete certain lazy proxies/unloaded entities without loading them, but under JPA bootstrap (EntityManagerFactory-built factory) it must enforce the JPA rule that remove() targets a managed entity. When the delete target's EntityKey is not present in the persistence context at all, it throws IllegalArgumentException('Given entity is not associated with the persistence context').

Source

Thrown at hibernate-core/src/main/java/org/hibernate/event/internal/DefaultDeleteEventListener.java:95

	}

	private boolean optimizeUnloadedDelete(@Nonnull DeleteEvent event) {
		final Object object = event.getObject();
		final var lazyInitializer = extractLazyInitializer( object );
		if ( lazyInitializer != null && lazyInitializer.isUninitialized() ) {
			final var source = event.getSession();
			final var factory = event.getFactory();
			final var persister =
					factory.getMappingMetamodel()
							.findEntityDescriptor( lazyInitializer.getEntityName() );
			final Object id = lazyInitializer.getInternalIdentifier();
			final var key = source.generateEntityKey( id, persister );
			final var persistenceContext = source.getPersistenceContextInternal();
			final var entityHolder = persistenceContext.getEntityHolder( key );
			if ( ( entityHolder == null || entityHolder.getEntity() == null || !entityHolder.isInitialized() )
					&& canBeDeletedWithoutLoading( source, persister ) ) {
				if ( factory.getSessionFactoryOptions().isJpaBootstrap() && entityHolder == null ) {
					throw new IllegalArgumentException( "Given entity is not associated with the persistence context" );
				}
				// optimization for deleting certain entities without loading them
				persistenceContext.reassociateProxy( object, id );
				if ( !persistenceContext.containsDeletedUnloadedEntityKey( key ) ) {
					persistenceContext.registerDeletedUnloadedEntityKey( key );
					if ( persister.hasOwnedCollections() ) {
						// we're deleting an unloaded proxy with collections
						for ( var type : persister.getPropertyTypes() ) { //TODO: when we enable this for subclasses use getSubclassPropertyTypeClosure()
							deleteOwnedCollections( type, id, source );
						}
					}
					source.getActionQueue().addAction( new EntityDeleteAction( id, persister, source ) );
				}
				return true;
			}
		}
		return false;
	}

View on GitHub (pinned to fad1729dce)

Solutions

  1. Reattach first: em.remove(em.merge(entity))
  2. Or load then delete inside the same context: em.remove(em.find(X.class, id))
  3. For bulk deletion by key, use a JPQL DELETE query instead of entity removal
  4. Do not mix entity instances across EntityManager lifecycles

Example fix

// before
em.remove(detachedCustomer); // IllegalArgumentException

// after
em.remove(em.merge(detachedCustomer));
Defensive patterns

Strategy: validation

Validate before calling

if (!em.contains(entity)) {
    entity = em.merge(entity); // reattach so remove() sees a managed entity
}
em.remove(entity);

Type guard

static <T> T managedOrMerged(EntityManager em, T entity) {
    return em.contains(entity) ? entity : em.merge(entity);
}

Prevention

When it happens

Trigger: em.remove(detachedEntity) where the entity was detached via em.detach()/clear() or created in another EntityManager; em.remove(em.getReference(X.class, id)) after the context was cleared; removing a proxy whose target was never loaded and whose key was evicted from the context.

Common situations: Two-EntityManager flows (load in one, remove in another); long conversation patterns where entities detach between operations; code migrating from native Session.delete() (which tolerated detached instances) to JPA remove().

Related errors


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