{"record":{"id":"982dd32ff0567348","repo":"hibernate/hibernate-orm","slug":"select-item-was-of-wrong-entity-type-982dd3","errorCode":null,"errorMessage":"Select item was of wrong entity type","messagePattern":"Select item was of wrong entity type","errorType":"exception","errorClass":"IllegalQueryOperationException","httpStatus":null,"severity":"error","filePath":"hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmUtil.java","lineNumber":930,"sourceCode":"\t\treturn createSortSpecification( sqm, order, items, selected );\n\t}\n\n\tprivate static SqmSortSpecification createSortSpecification(\n\t\t\tAbstractSqmSelectQuery<?> sqm, Order<?> order, List<SqmSelectableNode<?>> items, SqmSelectableNode<?> selected) {\n\t\tfinal var builder = sqm.nodeBuilder();\n\t\tif ( order.entityClass() == null ) {\n\t\t\t// ordering by an element of the select list\n\t\t\treturn new SqmSortSpecification(\n\t\t\t\t\tnew SqmAliasedNodeRef( order.element(), builder.getIntegerType(), builder ),\n\t\t\t\t\torder.direction(), order.nullPrecedence(), !order.caseSensitive()\n\t\t\t);\n\t\t}\n\t\telse {\n\t\t\t// ordering by an attribute of the returned entity\n\t\t\tif ( items.size() <= 1) {\n\t\t\t\tif ( selected instanceof SqmFrom<?, ?> root ) {\n\t\t\t\t\tif ( !order.entityClass().isAssignableFrom( root.getJavaType() ) ) {\n\t\t\t\t\t\tthrow new IllegalQueryOperationException(\"Select item was of wrong entity type\");\n\t\t\t\t\t}\n\t\t\t\t\tfinal StringTokenizer tokens = new StringTokenizer( order.attributeName(), \".\" );\n\t\t\t\t\tSqmPath<?> path = root;\n\t\t\t\t\twhile ( tokens.hasMoreTokens() ) {\n\t\t\t\t\t\tpath = path.get( tokens.nextToken() );\n\t\t\t\t\t}\n\t\t\t\t\treturn builder.sort( path, order.direction(), order.nullPrecedence(), !order.caseSensitive() );\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new IllegalQueryOperationException(\"Select item was not an entity type\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new IllegalQueryOperationException(\"Query has multiple items in the select list\");\n\t\t\t}\n\t\t}\n\t}\n","sourceCodeStart":912,"sourceCodeEnd":948,"githubUrl":"https://github.com/hibernate/hibernate-orm/blob/fad1729dce015f908198d57a8d80274a30f905a5/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmUtil.java#L912-L948","documentation":"Thrown as IllegalQueryOperationException when applying an org.hibernate.query.Order that is anchored to an entity class (Order.asc(Class, attributeName) / Order.by(...)) while the query's single select item is an entity root of a different, non-assignable Java type. Before sorting by 'attribute of the returned entity', SqmUtil checks order.entityClass().isAssignableFrom(root.getJavaType()); a mismatch means you asked to order the result by an attribute of an entity the query does not return.","triggerScenarios":"session.createQuery(\"select p from Person p\", Person.class).addOrder(Order.asc(Address.class, \"city\")); a generic DAO/grid component receives the sort entity class from the caller and it does not match the entity being queried; ordering by a completely unrelated class instead of the queried entity or its supertype.","commonSituations":"Reusable list endpoints where the sort specification (entity class + attribute name) arrives from the frontend or configuration; refactoring an entity while stale Order.by(OldEntity.class, ...) call sites remain; copy-pasting an order clause from another query.","solutions":["Pass the entity class the query actually returns: Order.asc(Person.class, \"name\")","Order by element position instead: Order.by(1, SortDirection.ASCENDING)","Put the sort into the HQL directly: 'order by p.name'","For polymorphic queries, order by an attribute declared on the queried root or its supertype"],"exampleFix":"// before\nList<Person> people = session.createSelectionQuery(\"select p from Person p\", Person.class)\n        .addOrder(Order.asc(Address.class, \"city\"))\n        .getResultList();\n// after\nList<Person> people = session.createSelectionQuery(\"select p from Person p\", Person.class)\n        .addOrder(Order.asc(Person.class, \"name\"))\n        .getResultList();","handlingStrategy":"validation","validationCode":"static <X> boolean orderAppliesToResult(Order<X> order, Class<?> resultType) {\n    Class<X> entity = order.entityClass();\n    return entity == null || entity.isAssignableFrom(resultType);\n}\n\nif (!orderAppliesToResult(order, Person.class)) {\n    throw new IllegalArgumentException(\"Order entity \" + order.entityClass() + \" does not match query result \" + Person.class);\n}","typeGuard":"static boolean isEntityAnchoredOrderFor(Order<?> order, Class<?> selectItemType) {\n    return order.entityClass() != null && order.entityClass().isAssignableFrom(selectItemType);\n}","tryCatchPattern":"try {\n    query.addOrder(order).getResultList();\n} catch (IllegalQueryOperationException e) {\n    // order spec does not fit this query: fall back to no explicit order or a safe default\n    query.getResultList();\n}","preventionTips":["Derive the Order's entity class from the same constant/class used to build the query","Unit-test sorting specs against the query's entity type","Prefer Order.by(element, direction) for projection queries"],"tags":["hibernate","order-by","query-api","orm"],"backgroundTag":"invalid-order-by-clause","analyzedSha":"fad1729dce015f908198d57a8d80274a30f905a5","analyzedAt":"2026-08-22T04:13:57.527Z","schemaVersion":2},"datasetVersion":"2026-08-22T09:17:25.309Z"}