hibernate对分页查询的支持

      本例模仿部门与员工进行查询,下面是进行Junit测试的核心代码

package cn.itcast.a_query;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.ScrollableResults;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;

public class App_page {
	private static SessionFactory sf;
	static{
		sf=new Configuration()
		.configure()
		.addClass(Dept.class)
		.addClass(Employee.class)
		.buildSessionFactory();
	}
	//分页查询
	@Test
	public void all() throws Exception{
		Session session=sf.openSession();
		session.beginTransaction();
		
		Query q=session.createQuery("from Employee");
		//从记录数得到滚动的结果集
	    ScrollableResults scroll=q.scroll();
		scroll.last();//滚动到最后一行
		int totalCount=scroll.getRowNumber()+1;//得到滚动的记录数,即总记录数
		//设置分页参数
		q.setFirstResult(0);
		q.setMaxResults(3);
		System.out.println(q.list());
		System.out.println("总记录数:"+totalCount);

		
		session.getTransaction().commit();
		session.close();
	}	
}


你可能感兴趣的:(hibernate)