Pagination Example Hibernate


Pagination Hibernate Tutorial

If Hibernate fetches large amount of data (records) from the database, it consumes lot of memory. To consume less RAM memory, the data can be obtained in installments from the database. One solution is using pagination

.

The idea behind Pagination Hibernate is to divide the large result set into a number of pages and fetching one page at a time. We can programmatically declare how many records should contain each page and from what record. For example, the page may contain 5 records staring from 3rd record.

The code is simple to do the job of Pagination Hibernate.

Query q = session.createQuery("select * from Student");  // you can use order by also 
q.setFirstResult(3);    	                         // starting position of the record (first record is 0, that is, 0, 1, 2, 3)
q.setMaxResults(5);   	                                 // size of page; each page displays 5 records (3, 4, 5, 6, 7)
List list1 = q.list();  	                         // iterate the list to get each page with Iterator or for loop

Previous First program – Student is used. Just change the client program.

Think there are 7 records (counting 0 to 6) in school table. We make three pages where 2 records, 3 records and 3 records are fetched each time (three database hits are made). End fetching gets only 2 records.

Program on Pagination
File Name: PaginationClient,java

import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class PaginationClient 
{
  public static void main(String[] args)  
  {
    Configuration c = new Configuration();
    c.configure("/hibernate.cfg.xml");
    SessionFactory sf = c.buildSessionFactory();
    Session s = sf.openSession();

    List result = null;
    try 
    {
      Query q = s.createQuery("from Student");
      q.setFirstResult(0);
      q.setMaxResults(2);
      result = q.list();                // first two records, 0 and 1
                                        // printing records using Iterator 
      Iterator it = result.iterator();
      while(it.hasNext())
      {
        Student std = (Student) it.next();
        System.out.println(std.getSid() + "  " + std.getSname() + "  " + std.getSmarks()+ " " + std.getSjoindate());
      }
           
      q.setFirstResult(2);
      q.setMaxResults(3);               // now you get 3 records starting from 2nd (0, 1, 2)
      result = q.list();                // next three records, 2, 3 and 4
			                // printing elements with JDK 1.5 enhanced for loop
      for(Student std : result)
      {
        System.out.println(std.getSid() + "  " + std.getSname() + "  " + std.getSmarks()+ " " + std.getSjoindate());
      }
           
      q.setFirstResult(5); 
   // q.setMaxResults(3);               // this statement is not needed as earlier max results size is used
      result = q.list();                // next two records, 5 and 6 (but here, we get only two 
                                        // because total records are 7 (0 to 6))
      for(Student std : result)
      {
        System.out.println(std.getSid() + "  " + std.getSname() + "  " + std.getSmarks()+ " " + std.getSjoindate());
      }
    } 
    catch (Exception e) 
    {
      e.printStackTrace();
    }
   }
}  

Pagination Hibernate

Note 1: Observe, for each fetch, one database hit is made. First fetch 2 records, second fetch 3 records and last fetch 2 records are obtained.

Note 2: It saves time also (or increases performance); for a number of records (one page) only one database hit is made.

2 thoughts on “Pagination Example Hibernate”

  1. “Think there are 7 records (counting 0 to 6) in school table. We make three pages where 2 records, 3 records and 3 records are fetched each time.”
    Is it 3+3+2 = 7?

  2. Hi guys

    I have to implement pagination like when i enter 1 from url ,shoud fetch first 10 records and 2 means It should fetch next 10 records ,Please help me for the implementation with query.

Leave a Comment

Your email address will not be published.