Java examples on org.hibernate
- How do I create Hibernate's SessionFactory?
- How do I limit the Hibernate query result?
- How do I use Hibernate's Restriction.in criterion?
- How do I retrieve a list of Hibernate's persistent objects?
- How do I retrieve object from database in Hibernate?
- How do I delete persistent object in Hibernate?
- How do I store object in Hibernate?
- How do I use min, max, avg and sum Projections?
- How do I set the fetch mode for Criteria association?
- How do I add Restrictions to the Criteria object?
- How do I select a single record using Criteria?
- How do I create a pagination using Criteria?
- How do I count the total records using Projections?
- How do I order the Criteria query resultset?
- How do I create a Criteria object?
How do I create a pagination using Criteria?
To create a pagination or limit the resultset returned by the Criteria query we can use the setFirstResult() and setMaxResults() method. The setFirstResult() method defines the first row to start with and the setMaxResults() method defines the maximum number of records to read. Let's see the demo below.
package org.kodejava.example.hibernate.criteria;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.HibernateException;
import org.hibernate.Criteria;
import org.hibernate.cfg.AnnotationConfiguration;
import org.kodejava.example.hibernate.model.Track;
import java.util.List;
public class CriteriaPagingDemo {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().
configure("hibernate.cfg.xml").
buildSessionFactory();
}
catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static Session getSession() throws HibernateException {
return sessionFactory.openSession();
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
final Session session = getSession();
try {
Criteria criteria = session.createCriteria(Track.class);
//
// Set the first record index to read from the result set.
//
criteria.setFirstResult(0);
//
// Set the maximum number of records to read
//
criteria.setMaxResults(2);
List<Track> tracks = criteria.list();
for (Track track : tracks) {
System.out.println("Track = " + track.getTitle());
}
} finally {
session.close();
}
}
}