Hibernate分页的两种实现方法

本文实例讲述了Hibernate分页的两种实现方法。分享给大家供大家参考,具体如下:

1. criteria分页

public Page getPage(int currentPage,int pageSize,Criterion...crts){
Criteria c=session.createCriteria(House.class);
List list=null;
for (int i = 0; i < crts.length; i++) {
c.add(crts[i]);
}
c.setProjection(Projections.rowCount());
int totalRecord=Integer.valueOf(c.uniqueResult().toString());
c.setProjection(null);
c.setFirstResult((pageSize)*(currentPage-1));
c.setMaxResults(pageSize);
list=c.list();
Page page=new Page();
page.setCurrentPage(currentPage);
page.setPageSize(pageSize);
page.setTotalRecord(totalRecord);
page.setList(list);
return page;
}

2. hql分页

public Page getPage(int currentPage,int pageSize,String hql,Object...args){
String countHql="select count(*) "+hql.substring(hql.indexOf("from"));
Session session=HibernateUtil.getInstance().getSession();
Query query=session.createQuery(countHql);
for (int i = 0; i < args.length; i++) {
query.setParameter(i, args[i]);
}
int totalRecord=Integer.valueOf(query.uniqueResult()+"");
query=session.createQuery(hql);
for (int i = 0; i < args.length; i++) {
query.setParameter(i, args[i]);
}
query.setFirstResult(pageSize*(currentPage-1));
query.setMaxResults(pageSize);
List list=(List)query.list();
Page page=new Page();
page.setCurrentPage(currentPage);
page.setPageSize(pageSize);
page.setTotalRecord(totalRecord);
page.setList(list);
return page;
}

希望本文所述对大家基于Hibernate框架的Java程序设计有所帮助。

你可能感兴趣的:(Hibernate分页的两种实现方法)