Two implementations of Hibernate paging

  • 2020-05-07 19:44:27
  • OfStack

This article illustrates two implementations of Hibernate paging. Share with you for your reference, as follows:

1. criteria paging


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 paging


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<House> list=(List<House>)query.list();
Page page=new Page();
page.setCurrentPage(currentPage);
page.setPageSize(pageSize);
page.setTotalRecord(totalRecord);
page.setList(list);
return page;
}

I hope this article is helpful for you to design Java programs based on Hibernate framework.


Related articles: