gtludwig gtludwig - 12 days ago 6
Java Question

Hibernate pagination - how to get the next batch of results?

I understand pagination to improve performance on queries that, naturally, have a very large resultset.

I have the implemented paginatedList method that successfully returns the correct amount. But it seems more of a MySQL's

LIMIT
or SQLServer's
TOP
clause.

The method is thus implemented:

@SuppressWarnings("unchecked")
public List<T> paginatedList(int pageSize) {
Criteria criteria = getSession().createCriteria(persistentClass);
criteria.setFirstResult(0);
criteria.setMaxResults(pageSize);
return (List<T>) criteria.list();
}


And I call like this:

@Override
public List<AlertLog> findAll() {
return super.paginatedList(1000);
}


This implementation returns results 0 to 1000.

How to, on runtime, get the 1001st to 2000th and so on?

Answer

to get the next 1000 result you need to set firstResult to 1000 and maxresults to 1000, so it becomes..

criteria.setFirstResult(1000);
criteria.setMaxResults(noOfEntries);

Please make sure that the noOfEntries is less that the total count.