hibernate/hibernate-orm · error · WrongClassException

Object [id= ] was not of the specified subclass [ ] : class…

Error message

Object [id=%s] was not of the specified subclass [%s] : class of the given object did not match class of persistent copy

What it means

On merge, the managed target's concrete entity name differs from the detached source's entity name — the persistent copy belongs to a different class in the same inheritance tree than the object being merged (e.g. merging a subclass instance onto a base-class row).

Solutions

  1. Ensure the merged object's runtime class matches the subclass of the persistent copy for the given id.
  2. Load the persistent instance by id first and copy state onto it instead of merging a mismatched subclass instance.
Defensive patterns

Strategy: type-guard

When it happens

Trigger: Thrown when the runtime class of a passed object does not match the persistent subclass expected for its id.

Common situations: Typical situations: merging an object of the wrong subclass for an existing id; polymorphic associations where the id resolves to a different subclass.


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

Appendix: source

Thrown at hibernate-core/src/main/java/org/hibernate/event/internal/DefaultMergeEventListener.java:530

			}
		}
	}

	@Nonnull
	private static Object targetEntity(
			@Nonnull MergeEvent event,
			@Nonnull Object entity,
			@Nonnull EntityPersister persister,
			@Nullable Object id,
			@Nonnull Object result) {
		final var source = event.getSession();
		final String entityName = persister.getEntityName();
		final Object target = unproxyManagedForDetachedMerging( entity, result, persister, source );
		if ( target == entity) {
			throw new AssertionFailure( "entity was not detached" );
		}
		else if ( !source.getEntityName( target ).equals( entityName ) ) {
			throw new WrongClassException(
					"class of the given object did not match class of persistent copy",
					event.getRequestedId(),
					entityName
			);
		}
		else if ( isVersionChanged( entity, source, persister, target ) ) {
			final var statistics = source.getFactory().getStatistics();
			if ( statistics.isStatisticsEnabled() ) {
				statistics.optimisticFailure( entityName );
			}
			throw new StaleObjectStateException( entityName, id );
		}
		else {
			return target;
		}
	}

	@Nullable

View on GitHub (pinned to fad1729dce)