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.


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();

        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;

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

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.