hibernate/hibernate-orm · error · IllegalQueryOperationException

Select item was not an entity type

Error message

Select item was not an entity type

What it means

Thrown as IllegalQueryOperationException when an entity-anchored Order (Order.asc(Class, attributeName)) is applied to a query whose single select item is not an entity root — it is a scalar or path expression (e.g. p.name, a count, a literal). Ordering by 'attribute of the returned entity' only works when the select item is the entity itself (an SqmFrom); for scalar projections there is no entity to resolve attributeName against.

Source

Thrown at hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmUtil.java:940

					order.direction(), order.nullPrecedence(), !order.caseSensitive()
			);
		}
		else {
			// ordering by an attribute of the returned entity
			if ( items.size() <= 1) {
				if ( selected instanceof SqmFrom<?, ?> root ) {
					if ( !order.entityClass().isAssignableFrom( root.getJavaType() ) ) {
						throw new IllegalQueryOperationException("Select item was of wrong entity type");
					}
					final StringTokenizer tokens = new StringTokenizer( order.attributeName(), "." );
					SqmPath<?> path = root;
					while ( tokens.hasMoreTokens() ) {
						path = path.get( tokens.nextToken() );
					}
					return builder.sort( path, order.direction(), order.nullPrecedence(), !order.caseSensitive() );
				}
				else {
					throw new IllegalQueryOperationException("Select item was not an entity type");
				}
			}
			else {
				throw new IllegalQueryOperationException("Query has multiple items in the select list");
			}
		}
	}

	private static SqmSelectableNode<?> selectedNode(AbstractSqmSelectQuery<?> sqm, Order<?> order) {
		final int element = order.element();
		if ( element < 1) {
			throw new IllegalQueryOperationException("Cannot order by element " + element
					+ " (the first select item is element 1)");
		}
		final var querySpec = sqm.getQuerySpec();
		final var selectionItems = querySpec.getSelectClause().getSelectionItems();
		final int items = selectionItems.size();
		if ( items == 0 && element == 1 ) {

View on GitHub (pinned to fad1729dce)

Solutions

  1. Move the sort into the HQL: 'select p.name from Person p order by p.age'
  2. Order by select-list element position: Order.by(1, SortDirection.ASCENDING)
  3. Select the entity itself if you need entity-attribute ordering, then map to the DTO in Java

Example fix

// before
List<String> names = session.createSelectionQuery("select p.name from Person p", String.class)
        .addOrder(Order.asc(Person.class, "age"))
        .getResultList();
// after
List<String> names = session.createSelectionQuery("select p.name from Person p order by p.age", String.class)
        .getResultList();
Defensive patterns

Strategy: validation

Validate before calling

static boolean orderUsableOnProjection(Order<?> order, boolean selectItemIsEntity) {
    return order.entityClass() == null || selectItemIsEntity;
}
// for projection queries (select p.name), reject entity-anchored orders up front:
if (order.entityClass() != null && !selectItemIsEntity) {
    order = Order.by(1, SortDirection.ASCENDING);
}

Type guard

static boolean isEntitySelection(org.hibernate.query.sqm.tree.select.SqmSelectableNode<?> node) {
    return node instanceof org.hibernate.query.sqm.tree.from.SqmFrom<?, ?>;
}

Try / catch

try {
    query.addOrder(order).getResultList();
} catch (IllegalQueryOperationException e) {
    // projection cannot be ordered by entity attribute: rewrite as order-by element or inline SQL
    throw new IllegalArgumentException("Use element-based ordering for projection queries", e);
}

Prevention

When it happens

Trigger: session.createQuery("select p.name from Person p", String.class).addOrder(Order.asc(Person.class, "age")); projection queries (DTO constructors, count queries, single-column selects) combined with entity-attribute ordering; report queries that select scalars but reuse the ordering helper written for entity queries.

Common situations: A shared ordering utility that always builds Order.by(entityClass, attribute) is reused on projection queries; refactoring an entity query into a DTO projection without touching the order clause.

Related errors


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