java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.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 com.javacoderanch.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();
        }
    }
}