for a paged data (paginated) I need to return the total number of records matching my criteria and the results first page. this is useful to display information for the users and calculate the total number of pages to expect (on the client).
at the moment I run the same query twice, once for the total count and once for the actual records. I hope there is a more efficient way.
can these two queries be combined to one call to the database?
the count:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<VersionJpa> r = cq.from(VersionJpa.class);
Predicate p = cb.conjunction();
p = // some filtering code define by caller
cq.where(p);
cq.select(cb.count(r));
TypedQuery<Long> tq = em.createQuery(cq);
return tq.getSingleResult().intValue();
the page:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<VersionJpa> cq = cb.createQuery(VersionJpa.class);
Root<VersionJpa> root = cq.from(VersionJpa.class);
Predicate p = cb.conjunction();
p = // same filtering code as in the count above
cq.where(p);
TypedQuery<VersionJpa> tq = em.createQuery(cq);
// paginatong
tq.setFirstResults(first); // from caller
tq.setMaxResults(max); // from caller
return tq.getResultList();