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?
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>");
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With