java中的分页? [英] pagination in java?

查看:109
本文介绍了java中的分页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望数字以这种格式显示..

i want the numbers to be displayed in this format..

1 2 3 4 5
^

如果我在哪里按5,然后它应显示从5到10

1 2 3 4 5 ^
where if i press 5, then it should display from 5 to 10

5 6 7 8 9 10

5 6 7 8 9 10

直到最大记录可用。我只是想知道如何显示数字。

till the max records are available. i just want to know a how to do this for displaying numbers.

推荐答案

通常,您希望数据库为分页和排序做繁重的工作。以MySQL为例,你可以通过添加

Normally you want your database to do the heavy lifting for pagination and sorting. With MySQL for example you can get a page of results sorted by date by adding

ORDER BY date ASC LIMIT 5,5

到SQL查询结束时。如果您使用hibernate,您可以使用条件API以独立于供应商的方式执行此操作:

to the end of your SQL query. If you use hibernate you can do this in a vendor-independent way using the criteria API:

List<MyDomainClass> results = (List<MyDomainClass>) getSession()     
.createCriteria(MyDomainClass.class)
.setFirstResult(5)
.setMaxResults(5)
.addOrder(Order.asc("date"))
.list();

要显示分页导航,您还需要计算结果总数,以了解其中有多少页是:

To display a pagination navigation you also need to count the total number of results to know how many pages there are:

int count = (int) getSession()     
.createCriteria(MyDomainClass.class)
.setProjection(Projections.rowCount())
.list().get(0);

您可以为这两个搜索添加限制,例如,当您要对可添加的姓氏进行过滤时:

You can add restrictions to both searches, for example when you want to filter on lastname you could add:

.add(Restrictions.eq("lastname", "Smith")

(这需要添加到计数查询和列表查询中)。

(This needs to be added to both the count query and the list query).

当您知道结果总数,页面大小和当前页码时,您可以计算结果范围,如下所示:

When you know the total number of results, the pagesize and the current page number you can calculate the range of results like this :

// TODO: execute the count query here to determine totalResults
int totalPages = Math.ceil(totalResults / pageSize);
// show first page by default
int firstResult = 0;
if (currentPage >= 0 && currentPage < totalPages) {
    firstResult = currentPage * pageSize;    
}
// the number of items might be less than the page size (i.e. on the last page)
int count = Math.min(pageSize, totalResults - firstResult);        
// TODO: execute the list query here to get a page of data

如何显示导航由您决定。一些框架具有标准组件。否则,您将不得不考虑处理大量页面的方法。一种常见的方法是显示一系列的10个页码和向前/向后跳转以开始/跳转到结束链接。

How you display the navigation is up to you. Some frameworks have standard components for that. Otherwise you will have to think of a way to handle huge amounts of pages. A common approach is to show a range of say 10 page numbers and forward/backward jump to start/jump to end links.

希望这会有所帮助。

这篇关于java中的分页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆