How do I limit the Hibernate query result?
Category: org.hibernate, viewed: 24439 time(s).
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 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;
}
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);
}
}
}
Can't find what you are looking for? Join our
FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources
Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more;
all available at no cost to you. With more than 600 complimentary offers, you'll find
plenty of titles to suit your professional interests and needs.
Click Here and Sign up today!