简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM