(Hibernate的分页做得很好很强大,用的人都知道
![基于JDBC的通用分页实现 - 北一止水 - 基于JDBC的通用分页实现 - 北一止水 -](http://lixor.iteye.com/images/smiles/icon_smile.gif)
1.为什么要分页?
2.有哪些分页技术?
a)存储过程分页
b)数据库专有sql特性分页
(为什么非要跨数据库平台呢?好吧,如果你的项目确定是不会换数据库的那就这么写吧。)
c)纯JDBC分页
d)根据数据库类型自动生成数据库专有特性的sql语句
我们来理一理分页的逻辑吧
首先,对用户而言他是不关心你是怎么分页的,他只要给你一个页码,然后你把那一页的记录给他就行了。
为了能够取得指定页码所对应的记录,我们还需要两个关键的参数:每页记录数、总记录数。
通过这两个参数能够计算出来总页数,同时也就可以判断用户给出的页码是否有效了(超出最后一页或者小于第一页),然后根据页码和每页记录数就可以算出来当前页的记录起止范围了。(这些个算术都是小学的,就不用说了吧,其实我也是想了半天的)
为了表示方便,就把这些参数写成一个类,同时把计算方法也写进去
-
- public
class Page { -
private int rowTotal;// 总记录数 -
private int pageSize = 10;// 每页记录数 -
-
private int count;// 当前页码 -
-
private int total;// 总页数 -
private int beginIndex;//起始记录下标 -
private int endIndex;//截止记录下标 -
-
-
public Page(int totalRow, int count) { -
this.rowTotal = totalRow; -
this.count = count; -
calculate(); -
} -
-
-
public Page(int totalRow, int count, int pageSize) { -
this.rowTotal = totalRow; -
this.count = count; -
this.pageSize = pageSize; -
calculate(); -
} -
-
private void calculate() { -
total = rowTotal / pageSize + ((rowTotal % pageSize) > 0 ? 1 : 0); -
-
if (count > total) { -
count = total; -
} else if (count < 1) { -
count = 1; -
} -
-
beginIndex = (count - 1) * pageSize ; -
endIndex = beginIndex + pageSize ; -
if (endIndex > rowTotal) { -
endIndex = rowTotal; -
} -
}