hibernate/hibernate-orm · error · IllegalArgumentException

Root entity of type ' ' did not have the given type

Error message

Root entity of type '%s' did not have the given type '%s'

What it means

Type check in castRoot: the located root entity's Java type is not assignable to the requested type parameter (or its type was null), so the root cannot be safely cast.

Solutions

  1. Verify the root entity's type before calling the typed access: the root must be assignable to the requested type.
  2. Pass the correct expected type (the entity class used when the root was created, or a subclass of it).
  3. If the alias refers to a different root than intended, list the roots and pick the one with the matching entity type.
Defensive patterns

Strategy: type-guard

When it happens

Trigger: A root entity was resolved by alias but its entity type does not match the type requested by the caller (treat/narrow by type).

Common situations: Requesting a root of an unrelated subclass, or confusing two roots with similar aliases in a multi-root criteria query.


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

Appendix: source

Thrown at hibernate-core/src/main/java/org/hibernate/query/sqm/tree/spi/select/AbstractSqmSelectQuery.java:299

	 */
	@Nonnull
	public <E> JpaRoot<? extends E> getRoot(String alias, Class<E> type) {
		for ( var root : getQuerySpec().getRootList() ) {
			final String rootAlias = root.getAlias();
			if ( rootAlias != null && rootAlias.equals( alias ) ) {
				return castRoot( root, type );
			}
		}
		throw new IllegalArgumentException( "No root entity with alias " + alias );
	}

	private static <E> JpaRoot<? extends E> castRoot(JpaRoot<?> root, Class<E> type) {
		final var rootEntityType = root.getJavaType();
		if ( rootEntityType == null ) {
			throw new AssertionFailure( "Java type of root entity was null" );
		}
		if ( !type.isAssignableFrom( rootEntityType ) ) {
			throw new IllegalArgumentException( "Root entity of type '" + rootEntityType.getTypeName()
												+ "' did not have the given type '" + type.getTypeName() + "'");
		}
		@SuppressWarnings("unchecked") // safe, we just checked
		final var result = (JpaRoot<? extends E>) root;
		return result;
	}

	@Nonnull
	@Override
	public <X> SqmRoot<X> from(@Nonnull Class<X> entityClass) {
		return addRoot(
				new SqmRoot<>(
						nodeBuilder().getDomainModel().entity( entityClass ),
						generateAlias(),
						true,
						nodeBuilder()
				)
		);

View on GitHub (pinned to fad1729dce)