把分页提出来放在工具包utils中,便于代码多次重复利用,只需传入参数即可。。
代码如下:
package www.csdn.project.util;
import java.util.ArrayList;
import java.util.List;
/**
* Pageination 2013-3-7 下午11:14:04
*
* @author 乔晓松
*
*/
public class Pagination<T> extends BaseHibernateDAO {
private static final Integer PAGESIZE = 2;
private Integer countPage;
private Integer nowPage;
private Integer countRecond;
private List<T> entities;
public Pagination(Class<T> className, int nowPage) {
this.countRecond = getCountRecord(className);
this.nowPage = nowPage;
this.countPage = this.countRecond % PAGESIZE == 0 ? this.countRecond
/ PAGESIZE : this.countRecond / PAGESIZE + 1;
this.entities = getNowPageInfo(this.nowPage, className);
}
public Integer getCountPage() {
return countPage;
}
public void setCountPage(Integer countPage) {
this.countPage = countPage;
}
public Integer getNowPage() {
return nowPage;
}
public void setNowPage(Integer nowPage) {
this.nowPage = nowPage;
}
public Integer getCountRecond() {
return countRecond;
}
public void setCountRecond(Integer countRecond) {
this.countRecond = countRecond;
}
public List<T> getEntities() {
return entities;
}
public void setEntities(List<T> entities) {
this.entities = entities;
}
public Integer getCountRecord(Class<T> className) {
int i = 0;
try {
i = Integer.parseInt(this
.getSession()
.createQuery(
"select count(c) from " + className.getName()
+ " c").uniqueResult().toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
HiberSessionFactory.closeSession();
}
return i;
}
@SuppressWarnings("unchecked")
public List<T> getNowPageInfo(Integer nowpage, Class<T> className) {
List<T> entities = new ArrayList<T>();
try {
entities = this.getSession().createCriteria(className)
.setFirstResult((nowpage - 1) * PAGESIZE)
.setMaxResults(PAGESIZE).list();
} catch (Exception e) {
e.printStackTrace();
} finally {
HiberSessionFactory.closeSession();
}
return entities;
}
}