Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I distinct count query by field in JPA specification?

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?

like image 814
Kepasnik Avatar asked Oct 18 '18 10:10

Kepasnik


1 Answers

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>");
    }
    ...
}
like image 172
Rafael Gava Avatar answered Nov 20 '22 12:11

Rafael Gava