hibernate_分页查询

 @Test
public void test() {
    SessionFactory sf = null;
    Session session = null;
    Transaction ts = null;
    try {
        sf = HibernateUtil.getSessionFactory();
        session = sf.getCurrentSession();
        ts = session.beginTransaction();    // 开始事务
        // Query query = session.createQuery("from User as u where (u.age > (select avg(u.age) from User as u)) ");
        // Query query = session.createQuery("from User as u order by u.birthday,u.name desc");
        // Query query = session.createQuery("select u.gender, avg(u.age), count(*) from User as u group by u.gender having avg(u.age) > 21 ");
        // Query query = session.createQuery("from User as u where u.name like ?1 and u.age > ?2");
        //query.setParameter(1, "%张%");
        //query.setParameter(2, 10);
        
        Query query = session.createQuery("from User");
        
        int n1 = 3, n2 = 10;    // 每页十条记录,查询第三页
        /*
        * setFirstResult下标从0开始计算,第n1页前,共n2*(n1-1)条记录
        * 当前记录id应该为n2*(n1-1)+1
        * 下标从零开始计算,所以传参应该为:n2*(n1-1)+1-1=n2*(n1-1)
        */ 
        query.setFirstResult(n2 * (n1 - 1)).setMaxResults(n2); 
        
        List list = query.list();
        for (int i = 0; i < list.size(); ++i) 
            System.out.println(list.get(i));
        ts.commit();    // 提交事务
    } catch (Exception e) {
        e.printStackTrace();
        if (ts != null) {
            ts.rollback();  // 回滚
        }
    } 
}

你可能感兴趣的:(hibernate)