hibernate/hibernate-orm · error · NonUniqueObjectException

A different object with the same identifier value was alread

Error message

A different object with the same identifier value was already associated with this persistence context

What it means

Error "A different object with the same identifier value was already associated with this persistence context" thrown in hibernate/hibernate-orm.

Source

Thrown at hibernate-core/src/main/java/org/hibernate/event/internal/DefaultLoadEventListener.java:209

			final var session = event.getSession();
			if ( session.getPersistenceContextInternal().getEntry( instanceToLoad ) != null ) {
				throw new PersistentObjectException(
						"attempted to load into an instance that was already associated with the session: "
								+ infoString( persister, event.getEntityId(), event.getFactory() )
				);
			}
			persister.setIdentifier( instanceToLoad, event.getEntityId(), session );
		}

		final Object entity = doLoad( event, persister, keyToLoad, options );
		final boolean isOptionalInstance = instanceToLoad != null;
		if ( entity == null
				&& ( !options.isAllowNulls() || isOptionalInstance ) ) {
			event.getFactory().getEntityNotFoundDelegate()
					.handleEntityNotFound( event.getEntityClassName(), event.getEntityId() );
		}
		else if ( isOptionalInstance && entity != instanceToLoad ) {
			throw new NonUniqueObjectException( event.getEntityId(), event.getEntityClassName() );
		}
		return entity;
	}

	/**
	 * Based on configured options, will either return a pre-existing proxy,
	 * generate a new proxy, or perform an actual load.
	 *
	 * @param event The initiating load request event
	 * @param persister The persister corresponding to the entity to be loaded
	 * @param keyToLoad The key of the entity to be loaded
	 * @param options The defined load options
	 *
	 * @return The result of the proxy/load operation.
	 */
	@Nullable
	private Object proxyOrLoad(
			@Nonnull LoadEvent event,

View on GitHub (pinned to fad1729dce)

Solutions

  1. Use merge() instead of persist()/load() when a detached instance with the same identifier may already be in the persistence context.
  2. Call session.clear() or evict() the conflicting instance before reattaching.
  3. Ensure each entity with a given id is loaded only once per session.

When it happens

Trigger: Thrown when two distinct object instances with the same persistent identity would coexist in one persistence context.

Common situations: Typical situations: loading an entity while a detached copy with the same id is re-attached; merging a copy while the managed instance is already present; duplicate instances produced by manual construction.


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