Possible regression 5.6 to 6.1 - [SqmRoot not yet resolved to TableGroup]

What you are doing here is illegal according to the JPA spec. Also see the java doc of CriteriaQuery#getRoots:

    /**
     * Return the query roots.  These are the roots that have
     * been defined for the <code>CriteriaQuery</code> or <code>Subquery</code> itself,
     * including any subquery roots defined as a result of
     * correlation. Returns empty set if no roots have been defined.
     * Modifications to the set do not affect the query.
     * @return the set of query roots
     */   
    Set<Root<?>> getRoots();

The error essentially is, that something in your query (select item) refers to nodes (SqmRoot) which are not part of the `CriteriaQuery.

The operation countQuery.getRoots().addAll(query.getRoots()); doesn’t do anything to the CriteriaQuery as per the java doc.

If you want, you can create a JIRA issue to improve the error message, but the code you wrote won’t work anymore in 6.0. If it worked before, then this was in violation to the JPA specification.

With 6.1 you can make use of the derived subquery support though to implement this. You can use code similar to the following:

CriteriaQuery<Long> countQuery = builder.createQuery(Long.class);
JpaSubQuery<Tuple> subquery = countQuery.subquery(Tuple.class);
// Apply everything from context.query also to subquery
JpaRoot<Tuple> root = countQuery.from(subquery);
countQuery.select(builder.count(root));

If you can’t apply everything from context.query to subquery for whatever reason, then you’ll have to find a different solution, but note that you can make use of the copy functionality of the SQM query model to easily do this. This would look something like this:

SqmSubQuery<Tuple> subquery = (SqmSubQuery<Tuple>) countQuery.subquery(Tuple.class);
SqmSelectStatement originalQuery = (SqmSelectStatement) context.query;
SqmQuerySpec querySpec = originalQuery.getQuerySpec();
subquery.setQueryPart(querySpec.copy(SqmCopyContext.simpleContext()));