Hibernate分页的两种实现方法
本文实例讲述了Hibernate分页的两种实现方法。分享给大家供大家参考,具体如下:
1.criteria分页
publicPagegetPage(intcurrentPage,intpageSize,Criterion...crts){ Criteriac=session.createCriteria(House.class); Listlist=null; for(inti=0;i<crts.length;i++){ c.add(crts[i]); } c.setProjection(Projections.rowCount()); inttotalRecord=Integer.valueOf(c.uniqueResult().toString()); c.setProjection(null); c.setFirstResult((pageSize)*(currentPage-1)); c.setMaxResults(pageSize); list=c.list(); Pagepage=newPage(); page.setCurrentPage(currentPage); page.setPageSize(pageSize); page.setTotalRecord(totalRecord); page.setList(list); returnpage; }
2.hql分页
publicPagegetPage(intcurrentPage,intpageSize,Stringhql,Object...args){ StringcountHql="selectcount(*)"+hql.substring(hql.indexOf("from")); Sessionsession=HibernateUtil.getInstance().getSession(); Queryquery=session.createQuery(countHql); for(inti=0;i<args.length;i++){ query.setParameter(i,args[i]); } inttotalRecord=Integer.valueOf(query.uniqueResult()+""); query=session.createQuery(hql); for(inti=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(); Pagepage=newPage(); page.setCurrentPage(currentPage); page.setPageSize(pageSize); page.setTotalRecord(totalRecord); page.setList(list); returnpage; }
希望本文所述对大家基于Hibernate框架的Java程序设计有所帮助。