要创建分页或限制Criteria查询返回的结果集,我们可以使用setFirstResult()andsetMaxResults()方法。该setFirstResult()方法定义了第一行,该setMaxResults()方法定义了要读取的最大记录数。让我们看下面的演示。
package org.nhooo.example.hibernate.criteria; import org.hibernate.SessionFactory; import org.hibernate.Session; import org.hibernate.HibernateException; import org.hibernate.Criteria; import org.hibernate.cfg.Configuration; import org.nhooo.example.hibernate.model.Track; import java.util.List; public class CriteriaPagingDemo { public static Session getSession() throws HibernateException { String cfg = "hibernate.cfg.xml"; SessionFactory sessionFactory = new Configuration().configure(cfg) .buildSessionFactory(); return sessionFactory.openSession(); } @SuppressWarnings("unchecked") public static void main(String[] args) { try (Session session = getSession()) { Criteria criteria = session.createCriteria(Track.class); // 设置第一个记录索引以从结果集中读取。 criteria.setFirstResult(0); // 设置要读取的最大记录数 criteria.setMaxResults(2); List<Track> tracks = criteria.list(); for (Track track : tracks) { System.out.println("Track = " + track.getTitle()); } } } }