简体   繁体   English

我们如何使用JPA计算最后一页?

[英]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 我想在我的Servlet / EJB / JPA-Hibernate项目中实现分页,但我无法弄清楚查询中只有一个页面如何知道我必须显示的页数

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) (Hibernate是我的JPA提供者,但如果可能,我更愿意只使用JPA)

UPDATE: COUNT() seems to be the better/easiest solution; 更新:COUNT()似乎是更好/最简单的解决方案; but what can be the cost of SELECT COUNT(*) FROM ... in comparison with executeQuery("SELECT * FROM ...).getListResult().size() ? 但与executeQuery("SELECT * FROM ...).getListResult().size()相比, SELECT COUNT(*) FROM ...的成本是executeQuery("SELECT * FROM ...).getListResult().size()

AFAIK, you need to either (1) count or (2) retrieve the complete hit list and do pagination in-memory. AFAIK,您需要(1)计数或(2)检索完整的命中列表并在内存中进行分页。 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 有几种方法可以统计,一种是使用COUNT(*)

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 希望它有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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