JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Pagination using Hibernate and JSP

October 3, 2008 by JavaBeat Leave a Comment

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:

1)Download the latest version of hibernate from www.hibernate.org, and include all the required jars in your classpath.

2)Hibernate configuration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<code>
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
       "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
       "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
   <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
   <property name="connection.url">jdbc:oracle:thin:@localhost:1521/orcl</property>
   <property name="connection.username">scott</property>
   <property name="connection.password">tiger</property>
   <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
   <property name="hibernate.current_session_context_class">thread</property>
   <mapping resource="beans/Employee.hbm.xml" />
 </session-factory>
</hibernate-configuration>
</code>

<code> <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521/orcl</property> <property name="connection.username">scott</property> <property name="connection.password">tiger</property> <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> <property name="hibernate.current_session_context_class">thread</property> <mapping resource="beans/Employee.hbm.xml" /> </session-factory> </hibernate-configuration> </code>

3)The Employee bean class to hold the data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<code>
public class Employee {
 public long empId;
 public String empName;
 public String empJob;
 public long empSal;
 public long getEmpId() {
   return empId;
 }
 public void setEmpId(long empId) {
   this.empId = empId;
 }
 public String getEmpJob() {
   return empJob;
 }
 public void setEmpJob(String empJob) {
   this.empJob = empJob;
 }
 public String getEmpName() {
   return empName;
 }
 public void setEmpName(String empName) {
   this.empName = empName;
 }
 public long getEmpSal() {
   return empSal;
 }
 public void setEmpSal(long empSal) {
   this.empSal = empSal;
 }
}
</code>

<code> public class Employee { public long empId; public String empName; public String empJob; public long empSal; public long getEmpId() { return empId; } public void setEmpId(long empId) { this.empId = empId; } public String getEmpJob() { return empJob; } public void setEmpJob(String empJob) { this.empJob = empJob; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public long getEmpSal() { return empSal; } public void setEmpSal(long empSal) { this.empSal = empSal; } } </code>

4)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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<code>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
 <class name="beans.Employee" table="Emp">
   <id name="empId" column="EMPNO" type="long">
     <generator class="native"/>
   </id>
   <property name="empName" column="ENAME" />
   <property name="empJob" column="JOB" />
   <property name="empSal" column="SAL" type="long"/>
 </class>
</hibernate-mapping>
</code>

<code> <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="beans.Employee" table="Emp"> <id name="empId" column="EMPNO" type="long"> <generator class="native"/> </id> <property name="empName" column="ENAME" /> <property name="empJob" column="JOB" /> <property name="empSal" column="SAL" type="long"/> </class> </hibernate-mapping> </code>

5)The Data Access Object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<code>
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;
 }
}
</code>

<code> 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; } } </code>

6)The JSP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<code>
<jsp:root version="1.2" xmlns:jsp="http://java.sun.com/JSP/Page"
 xmlns:c="urn:jsptld:http://java.sun.com/jsp/jstl/core">
 <jsp:directive.page contentType="text/html; charset=UTF-8" />
 
 <link rel="stylesheet" type="text/css" href="css/screen.css" />
 <jsp:scriptlet>
     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);
 </jsp:scriptlet>
 <h2 align="center">Emp Table with Display tag</h2>
 <jsp:useBean id="EmpList" scope="session" type="java.util.List"></jsp:useBean>
 <table>
   <tr>
     <th>Employee Id</th>
     <th>Name</th>
     <th>Job</th>
     <th>Salary</th>
   </tr>
   <c:forEach items="${EmpList}" var="emp" begin="0" end="10">
     <tr>
       <td><c:out value="${emp.empId}"></c:out></td>
       <td><c:out value="${emp.empName}"></c:out></td>
       <td><c:out value="${emp.empJob}"></c:out></td>
       <td><c:out value="${emp.empSal}"></c:out></td>
     </tr>
   </c:forEach>
 
   <tr>
     <td colspan="2"></td>
     <td colspan="2"><a href="${pageScope.myUrl}">nextPage</a></td>
   </tr>
 </table>
</jsp:root>
</code>

<code> <jsp:root version="1.2" xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:c="urn:jsptld:http://java.sun.com/jsp/jstl/core"> <jsp:directive.page contentType="text/html; charset=UTF-8" /> <link rel="stylesheet" type="text/css" href="css/screen.css" /> <jsp:scriptlet> 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); </jsp:scriptlet> <h2 align="center">Emp Table with Display tag</h2> <jsp:useBean id="EmpList" scope="session" type="java.util.List"></jsp:useBean> <table> <tr> <th>Employee Id</th> <th>Name</th> <th>Job</th> <th>Salary</th> </tr> <c:forEach items="${EmpList}" var="emp" begin="0" end="10"> <tr> <td><c:out value="${emp.empId}"></c:out></td> <td><c:out value="${emp.empName}"></c:out></td> <td><c:out value="${emp.empJob}"></c:out></td> <td><c:out value="${emp.empSal}"></c:out></td> </tr> </c:forEach> <tr> <td colspan="2"></td> <td colspan="2"><a href="${pageScope.myUrl}">nextPage</a></td> </tr> </table> </jsp:root> </code>

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.

Filed Under: Hibernate Tagged With: pagination

Pagination in Hibernate Query API

July 26, 2008 by Krishna Srinivasan Leave a Comment

Pagination in Hibernate Query API

Pagination is the very common problem for the most of the eneterprise applications.When we are retrieving thousands of records from the database, it is not good idea to retrieve all the records at the same time. So, we have to implement some sort of pagination concept in your application to restrict the number of rows to be fetched from the database.

also read:

  • Introduction to Hibernate
  • Hibernate Interview Questions
  • Interceptors in Hibernate
  • Hibernate Books

Pagination can be done in the middle tier or in the database itself. if you are implementing the pagination in themidd letier, you have to retrieve all the records from the database and store it in the cache. It will take more memory and slow down the performance. So, it is good idea to implement in the database. However, it purely depends on the project requirement.
Hibernate APIs provide few methods to set the pagination citerias in the query. We can use bothe normal Query and Criteria API. Look into the following code for how to create pagination using the Query object:
[code lang=”java”]
Query query = session.createQuery("from Studenet s");
query.setFirstResult(25);
query.setMaxResults(50);
[/code]
[code lang=”java”]
Criteria criteria = session.createCriteria(Student.class);
criteria.setFirstResult(25);
criteria.setMaxResults(50);
List result = criteria.list();
[/code]

In the above code, both the techniques are telling the Hibernate query for how many records to be retrieved and first set of records. These values can be dynamically changed and we can obtain the pagination implementation.

Filed Under: Hibernate Tagged With: pagination

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved