views:

38

answers:

1

I would like to implement pagination in my Servlet/EJB/JPA-Hibernate project, but I can't figure out how only one page from the query and know the number of pages I must display

I use

setFirstResult(int first) ;
setMaxResults(int max) ;

and that's working alright, but how can I know how many pages I will have in total?

(Hibernate is my JPA provider, but I would prefer using only JPA if possible)

UPDATE: COUNT() seems to be the better/easiest solution; but what can be the cost of SELECT COUNT(*) FROM ... in comparison with executeQuery("SELECT * FROM ...).getListResult().size() ?

+2  A: 

AFAIK, you need to either (1) count or (2) retrieve the complete hit list and do pagination in-memory. The number of pages is the round up of the total count / the page size.

There are several ways to count, one is to use COUNT(*) like in

Query query=em.createQuery("SELECT COUNT
(emp.empName) FROM Employee emp");

or another oner is to use a projection

criteria.setProjection(Projections.rowCount());
int rowCount = (Integer) criteria.list().get(0);

Note that I never used this one though, I just read it somewhere.

I had documented a few other details about pagination in this answer:

Hope it help

ewernli