if (isFirstPage()) { // this is the first time we’re executing this query
Query q = em.createQuery(“SELECT COUNT(p) FROM Product p WHERE …”);
long count = ((Long) q.getSingleResult()).longValue();
// store count somewhere stateful
}
Query q = em.createQuery(“SELECT p FROM Product p WHERE …”);
q.setFirstResult(page * PAGE_SIZE); // page is stored somewhere stateful
q.setMaxResults(PAGE_SIZE);