Question: I have Specification class which implements JPA Specification interface:
`EntityClassSpecification implements Specification<EntityClass>`

I have overridden `toPredicate` method that looks like this:

```
public Predicate toPredicate(Root<EntityClass> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    final Collection<Predicate> predicates = new ArrayList<>();
    if (isNullOrEmpty(soilEntryCriteria.getField())) {
        query.groupBy(root.get("field"));
    }
    return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}

```

The problem is, when I'm using this Specification for findAll(), which returns `Page<EntityClass>` result set, grouped by `field`, but when I get total count for pagination - it returns incorrect count, without grouping by `field`.

I tried to use `.distinct(true)`, `.countDistinct(root.get("field"))` and creating separate count query, which returns Long value, but every time jpql query for count doesn't change, and returns incorrect total value.

I think its time to ask for some help. Could you please suggest any tips how I can change this total count query for pagination?

Answer: 
I'm using this approach:

```
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) 
{

    // Count Query?
    if (query.getResultType().toString().contains("java.lang.Long")) {
        root.join("<MyJoinEntity>");
    } else {
        root.fetch("<MyJoinEntity>");
    }
    ...
}

```
M.b. it's a little better (based on @Rafael Gava answer):

```
private static boolean isCountQuery(CriteriaQuery<?> query) {
    return query.getResultType().getAnnotation(Entity.class) == null;
}

```