我希望数字以这种格式显示..
1 2 3 4 5
^
如果我按 5,那么它应该显示 5 到 10
5 6 7 8 9 10
直到最大记录可用。我只想知道如何显示数字。
最佳答案
通常您希望数据库为分页和排序做繁重的工作。以 MySQL 为例,您可以获得按日期排序的结果页面,方法是添加
ORDER BY date ASC LIMIT 5,5
到 SQL 查询的末尾。如果您使用 hibernate ,则可以使用标准 API 以独立于供应商的方式执行此操作:
List<MyDomainClass> results = (List<MyDomainClass>) getSession()
.createCriteria(MyDomainClass.class)
.setFirstResult(5)
.setMaxResults(5)
.addOrder(Order.asc("date"))
.list();
要显示分页导航,您还需要计算结果总数以了解有多少页:
int count = (int) getSession()
.createCriteria(MyDomainClass.class)
.setProjection(Projections.rowCount())
.list().get(0);
您可以为这两个搜索添加限制,例如,当您想要过滤姓氏时,您可以添加:
.add(Restrictions.eq("lastname", "Smith")
(计数查询和列表查询都需要加上这个)
当您知道结果总数、页面大小和当前页码时,您可以像这样计算结果范围:
// 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 个页码和向前/向后跳转到开始/跳转到结束的链接。
希望这对您有所帮助。
关于java - java中的分页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5521835/