I'm trying to fetch results and also the row count inside a single query for pagination.
This is what I got so far:
public List<User> getUsers(int page, int size, boolean somecondition) {
Criteria criteria = getSession().getCurrentSession().createCriteria(User.class);
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.property("name").as("name"));
projectionList.add(Projections.property("createdAt").as("createdAt"));
projectionList.add(Projections.property("id").as("id"));
projectionList.add(Projections.rowCount());
projectionList.add(Projections.groupProperty("id"));
criteria.setProjection(projectionList);
// pseudo Restrictions added
if (somecondition) {
criteria.add(Restrictions.isNotNull("email"));
}
if (somecondition) {
criteria.add(Restrictions.isNotNull("name"));
}
// Now here do something to get the row count without doing a second query
long count;
ScrollableResults scrollableResults = criteria.scroll();
scrollableResults.last();
count = scrollableResults.getRowNumber() + 1;
scrollableResults.close();
log.info("users count : {}", count);
criteria.setMaxResults(size);
criteria.setFirstResult(page);
criteria.setResultTransformer(new AliasToBeanResultTransformer(User.class));
List<User> users = criteria.list();
users.forEach(u -> log.info(u.toString()));
return users;
}
I read that I could use ScrollableResults to get the row count without a second query, but that does not work, I still see in the console that there are 2 queries.
I'm not trying to get the total results, it's important to get the count of the results that satisfy the conditions.
Any suggestions ?