diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/select/SqmSelectStatement.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/select/SqmSelectStatement.java index 55ec360b10..c92455af9d 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/select/SqmSelectStatement.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/select/SqmSelectStatement.java @@ -483,16 +483,7 @@ public class SqmSelectStatement extends AbstractSqmSelectQuery implements return (SqmSelectStatement) copy; } else { - final JpaSelection selection = queryPart.getFirstQuerySpec().getSelection(); - if ( selection.isCompoundSelection() ) { - char c = 'a'; - for ( JpaSelection item : selection.getSelectionItems() ) { - item.alias( Character.toString( ++c ) + '_' ); - } - } - else { - selection.alias( "a_" ); - } + aliasSelections( queryPart ); final SqmSubQuery subquery = new SqmSubQuery<>( copy, queryPart, null, nodeBuilder() ); final SqmSelectStatement query = nodeBuilder().createQuery( Long.class ); query.from( subquery ); @@ -500,4 +491,30 @@ public class SqmSelectStatement extends AbstractSqmSelectQuery implements return query; } } + + private void aliasSelections(SqmQueryPart queryPart) { + if ( queryPart.isSimpleQueryPart() ) { + final SqmQuerySpec querySpec = queryPart.getFirstQuerySpec(); + final LinkedHashSet> newSelections = new LinkedHashSet<>(); + aliasSelection( querySpec.getSelection(), newSelections ); + //noinspection unchecked + querySpec.setSelection( (JpaSelection) ( newSelections.size() == 1 ? + newSelections.iterator().next() : + nodeBuilder().tuple( newSelections.toArray( new JpaSelection[0] ) ) ) ); + } + else { + ( (SqmQueryGroup) queryPart ).getQueryParts().forEach( this::aliasSelections ); + } + } + + private void aliasSelection(JpaSelection selection, LinkedHashSet> newSelections) { + if ( selection.isCompoundSelection() || selection instanceof SqmDynamicInstantiation ) { + for ( JpaSelection selectionItem : selection.getSelectionItems() ) { + aliasSelection( selectionItem, newSelections ); + } + } + else { + newSelections.add( selection.alias( "c" + newSelections.size() ) ); + } + } }