createCountQuery - aliased selection and dynamic instantiation error

when I try using createCountQuery with an HQL which uses a “dynamic” model
like SELECT new com.example.model(, e.other)

At first I get an error saying “aliases are required in CTEs and in subqueries occurring in from clause”
If I then manually set the aliases on the selection items with:

if (criteriaQuery.getQueryPart() instanceof SqmQueryPart<?> sqmQueryPart) {
      // hibernate createCountQuery requires aliases on the selection if it creates a subquery internally
      var selection = sqmQueryPart.getFirstQuerySpec().getSelection();
      char c = 'b';
      for (var item : selection.getSelectionItems()) {
        if (item.getAlias() == null) {
          item.alias(Character.toString(++c) + '_');

Then I get java.lang.UnsupportedOperationException: dynamic instantiation in a sub-query is unsupported

Is this a known issue or is there a known workaround (without having to specify the countQuery manually)?

I don’t think this is an issue, it’s simply a limitation imposed by how the createCountQuery API works: it’s a convenience method that, in very simple terms, generates a query like select count(1) from ( <original_query> ). Since your original query cointans a dynamic instantiation, you can’t use that directly.

I would suggest either:

  • Using createCountQuery with a different selection, e.g. selecting the same paths but without the dynamic instantiation itself;
  • Creating the count query yourself with HQL to ensure consistent results with your original one.

Please create a Jira issue for this and attach a reproducer based on our test case template.
Should be easy to support this.