本文实例讲述了Hibernate分页的两种实现方法。分享给大家供大家参考,具体如下:
1. criteria分页
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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分页
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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; } |
希望本文所述对大家基于Hibernate框架的Java程序设计有所帮助。