Tuesday, August 10, 2010

Pagination using Hibernate and JSP

If the result set is large, then having the entire result set in memory will not be feasible. With large result sets, you cannot afford to have them in memory. In such case, you have to fetch a chunk of data at a time (query based paging). The down side of using query based paging, is that there will be multiple calls to the database for multiple page requests. In this post, I will describe how to implement simple query based caching solution, using Hibernate and a simple JSP. Time permitting, I will soon post a hybrid of cache based and query based paging example. Here is the code for implementing simple paging using a JSP and Hibernate:

The Employee Mapping file: This listing of the Data Access Object uses the setMaxResults, and setFirstResult method of the Query object to extract the appropriate set of results for each page.

The Data Access Object



public class DAO {
private static int pageSize = 3;
public static List getData(int pageNumber) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
List result = null;
try {
session.beginTransaction();
Query query = session.createQuery("from Employee");
query = query.setFirstResult(pageSize * (pageNumber - 1));
query.setMaxResults(pageSize);
result = query.list();
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}

The JSP



int pageNumber=1;
if(request.getParameter("page") != null) {
session.setAttribute("page", request.getParameter("page"));
pageNumber = Integer.parseInt(request.getParameter("page"));
} else {
session.setAttribute("page", "1");
}
String nextPage = (pageNumber +1) + "";
session.setAttribute( "EmpList", data.DAO.getData(pageNumber));
System.out.println(((java.util.List)session.getAttribute("EmpList")).size());
String myUrl = "pagingEmp.jsp?page=" + nextPage;
System.out.println(myUrl);

pageContext.setAttribute("myUrl", myUrl);

Emp Table with Display tag


Employee Id Name Job Salary
nextPage
-->

This JSP uses the DAO class to retrieve the Employee information from the database. The page number is passed as a parameter to the DAO. Notice that I did not implement the "previous" page, but it is similar to next. I assumed that we do not know the number of results for this example.

No comments:

Post a Comment