How do I 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.

package org.kodejava.example.hibernate.app;

import org.hibernate.Query;
import org.hibernate.Session;
import org.kodejava.example.hibernate.model.Label;

import java.util.List;

public class LabelManager {

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

        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);
        query.setMaxResults(pageSize);

        List labels = query.list();
        session.getTransaction().commit();
        return labels;
    }
}
package org.kodejava.example.hibernate.app;

import org.kodejava.example.hibernate.model.Label;

import java.util.List;

public class LimitDemo {
    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);
        }
    }
}

Wayan Saryada

A programmer, a slow runner, a recreational open water diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.

Leave a Reply