java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to limit the Hibernate query result?

In the example below you'll see how to limit the number of records returned by the Hibernate queries. Limiting the query result usually used from created a pagination result where we can navigate from page to page in our application data but only a few data are read from the database.

In the Hibernate's Query object we need to specify the first result and max results by calling the setFirstResult() and setMaxResults() methods.


import org.hibernate.Query;
import org.hibernate.Session;

import java.util.List;

public class LabelManager {

    public List getLabels(Label label, int pageNumber, int pageSize) {
        Session session = SessionFactoryHelper.getSessionFactory().getCurrentSession();

        Query query = session.createQuery("from Label");

         * Set the first record position and the max number of record to be read.
         * The setFirstResult() tell hibernate from which row the data should be
         * read. In the example if we have pages of 10 records, passing the page
         * number 2 will read 10 records from the 20th row in the selected records.
        query.setFirstResult((pageNumber - 1) * pageSize);

        List labels = query.list();
        return labels;
    public static void main(String[] args) {        
        LabelManager manager = new LabelManager();

        List labels = manager.getLabels(null, 1, 10);
        for (int i = 0; i < labels.size(); i++) {
            Label label = (Label) labels.get(i);
            System.out.println("Label = " + label);