Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we compute the LAST page with JPA?

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() ?

like image 826
Kevin Avatar asked Oct 15 '22 04:10

Kevin


1 Answers

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:

  • client side sorting + hibernate paging

Hope it help

like image 188
ewernli Avatar answered Oct 31 '22 16:10

ewernli