tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Hibernate > Hibernate Query Language > Limit ResultSet Size

Limit ResultSet Size 

The following example shows how to limit the results returned by a query. It is useful to implement server side pagination. Refer first example for the configuration and mapping. Hibernate org.hibernate.Query provides the following APIs,

public Query setFirstResult(int firstResult)
 - Set the first row to retrieve. If not set, 
   rows will be retrieved beginnning from row 0. 
 
public Query setMaxResults(int maxResults)
 - Set the maximum number of rows to retrieve. If not set, 
   there is no limit to the number of rows retrieved.

File Name  :  
com/bethecoder/tutorials/hibernate/basic/tests/HQLMaxResultsTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.hibernate.basic.tests;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import com.bethecoder.tutorials.hibernate.basic.Company;
import com.bethecoder.tutorials.hibernate.basic.util.HibernateUtil;

public class HQLMaxResultsTest {

  private static final int PAGE_SIZE = 4;
  
  /**
   @param args
   */
  public static void main(String[] args) {

    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    
    String HQL_QUERY = "from Company comp";
    Query query = session.createQuery(HQL_QUERY);
    
    int curPage = 2;
    /**
     * Assuming page size of 4.
     
     * Page1 (1, 2, 3, 4)
     * Page2 (5, 6, 7, 8)
     * Page3 (9, 10, 11, 12)
     */
    query.setFirstResult((curPage-1* PAGE_SIZE)//set to start of page
    query.setMaxResults(PAGE_SIZE);

    List<Company> companies = query.list();    
    System.out.println("Selected row count : " + companies.size());
    
    for (Company company : companies) {
      System.out.println(company);
    }
    
    session.getTransaction().commit();
    session.close();
  }
  
}
   

It gives the following output,
Selected row count : 4
{ id = 5, name = ART, employeeCount = 67890, 
	projectCount = 850, address1 = add1112, address2 = add2223 }
{ id = 6, name = RNK, employeeCount = 98890, 
	projectCount = 8478, address1 = add1412, address2 = add27823 }
{ id = 7, name = AOQ, employeeCount = 97890, 
	projectCount = 4578, address1 = add17892, address2 = add2893 }
{ id = 8, name = BQO, employeeCount = 9778, 
	projectCount = 487, address1 = add1459, address2 = add2443 }



 
  


  
bl  br