In the example below you’ll see how to limit the number of records returned by hibernate queries. Limiting the query result is usually use for creating pagination, where we can navigate from page to page of data in our application but only a few of them are read from the database.
In hibernate Query
object we need to specify the first result and max results by calling the setFirstResult()
and setMaxResults()
methods to limit the query results.
package org.kodejava.hibernate.service;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.kodejava.hibernate.SessionFactoryHelper;
import org.kodejava.hibernate.model.Label;
import java.util.List;
public class LabelService {
public List<Label> getLabels(int pageNumber, int pageSize) {
Session session =
SessionFactoryHelper.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query<Label> query = session.createQuery("from Label", Label.class);
// 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<Label> labels = query.list();
session.getTransaction().commit();
return labels;
}
}
package org.kodejava.hibernate;
import org.kodejava.hibernate.model.Label;
import org.kodejava.hibernate.service.LabelService;
import java.util.List;
public class LimitDemo {
public static void main(String[] args) {
LabelService service = new LabelService();
List<Label> labels = service.getLabels(1, 10);
for (Label label : labels) {
System.out.println("Label = " + label);
}
}
}
Maven Dependencies
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.9.Final</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024