Skip to content

Commit d464bb7

Browse files
committed
HHH-19065 Account for entity valued paths in select for getResultCount
1 parent 944fb93 commit d464bb7

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

hibernate-core/src/main/java/org/hibernate/query/sqm/tree/select/SqmSelectStatement.java

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,11 @@
2525
import org.hibernate.query.sqm.tree.SqmCopyContext;
2626
import org.hibernate.query.sqm.tree.SqmStatement;
2727
import org.hibernate.query.sqm.tree.cte.SqmCteStatement;
28+
import org.hibernate.query.sqm.tree.domain.SqmEntityValuedSimplePath;
29+
import org.hibernate.query.sqm.tree.domain.SqmPath;
2830
import org.hibernate.query.sqm.tree.expression.ValueBindJpaCriteriaParameter;
2931
import org.hibernate.query.sqm.tree.expression.SqmParameter;
32+
import org.hibernate.query.sqm.tree.from.SqmFrom;
3033
import org.hibernate.query.sqm.tree.from.SqmFromClause;
3134
import org.hibernate.query.sqm.tree.predicate.SqmPredicate;
3235
import org.hibernate.query.sqm.tree.from.SqmRoot;
@@ -528,8 +531,9 @@ public SqmSelectStatement<Long> createCountQuery() {
528531
// in 'select' list (we don't even need to hit the database to
529532
// know they return exactly one row)
530533
if ( queryPart.isSimpleQueryPart()
531-
&& !( querySpec = (SqmQuerySpec<?>) queryPart ).isDistinct()
532-
&& querySpec.getGroupingExpressions().isEmpty() ) {
534+
&& !( querySpec = queryPart.getFirstQuerySpec() ).isDistinct()
535+
&& querySpec.getGroupingExpressions().isEmpty()
536+
&& !selectsEntityValuedPaths( querySpec ) ) {
533537
for ( SqmRoot<?> root : querySpec.getRootList() ) {
534538
root.removeLeftFetchJoins();
535539
}
@@ -553,6 +557,31 @@ public SqmSelectStatement<Long> createCountQuery() {
553557
}
554558
}
555559

560+
private static boolean selectsEntityValuedPaths(SqmQuerySpec<?> querySpec) {
561+
for ( SqmSelectableNode<?> selection : querySpec.getSelectClause().getSelectionItems() ) {
562+
if ( selection instanceof SqmEntityValuedSimplePath<?> entityPath ) {
563+
final SqmPath<?> lhs = entityPath.getLhs();
564+
if ( lhs instanceof SqmFrom<?, ?> from ) {
565+
// force an explicit inner join for this implicit entity valued path
566+
from.join( entityPath.getNavigablePath().getLocalName() );
567+
}
568+
else {
569+
return true;
570+
}
571+
}
572+
else if ( selection instanceof SqmPath<?> path ) {
573+
SqmPath<?> lhs = path.getLhs();
574+
while ( lhs != null ) {
575+
if ( lhs instanceof SqmEntityValuedSimplePath<?> ) {
576+
return true;
577+
}
578+
lhs = lhs.getLhs();
579+
}
580+
}
581+
}
582+
return false;
583+
}
584+
556585
private <S> void aliasSelections(SqmQueryPart<S> queryPart) {
557586
if ( queryPart.isSimpleQueryPart() ) {
558587
final SqmQuerySpec<S> querySpec = queryPart.getFirstQuerySpec();

0 commit comments

Comments
 (0)