Wednesday 3 August 2022

How to create A Pagination using Hibernate in Java








----------------------------- DAO.java ---------------------------------------

package com.ramsiscode;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Projections;


public class DAO {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
private static int pageSize = 8;
Session session = null;
public  List getData(int pageNumber) {
 
  //Session session = sessionFactory.getCurrentSession();
 
  List result = null;
  try {
session = sessionFactory.openSession();
    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();
  }finally{
  if(session!=null){
  session.close();
  }
  }
  return result;
}
 

  public  Long getMaxRow() {
  Long result = 0l;
 // SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  //Session session =null;
  try{
  session = sessionFactory.openSession();  
  session.beginTransaction();
  Criteria crit = session.createCriteria(Employee.class);
  crit.setProjection(Projections.rowCount());
 
  //result = session.createCriteria(Employee.class).setProjection(Projections.rowCount());
  //Query query = session.createQuery("select COUNT(empId) from Employee");
  session.getTransaction().commit();
 
  if(crit.list().size()>0)
  {
  result=   (Long) crit.list().get(0);
  }
 
  System.out.println("--------- rowCount -------- "+result);
 
 
  }catch(Exception e)
  {e.printStackTrace();}
  finally{
 if(session!=null){
  session.close();
  }
  }
  return result;
  }


private static Integer parseInt(Object object) {
// TODO Auto-generated method stub
return null;
}
}

------------------------------ Employee.java ------------------------

package com.ramsiscode;
import java.io.*;
public class Employee {
public long empId;
public String empName=null;
public String empJob=null;
public long empSal;
public long getEmpId() {
return empId;
}
public void setEmpId(long empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpJob() {
return empJob;
}
public void setEmpJob(String empJob) {
this.empJob = empJob;
}
public long getEmpSal() {
return empSal;
}
public void setEmpSal(long empSal) {
this.empSal = empSal;
}

}

---------------------------- PaginationCreateQueryControl.java -------------------------------

package com.ramsiscode;
import java.io.DataInputStream;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class PaginationCreateQueryControl {
private static  SessionFactory sessionFactory;
 private Session getSession()
 {
 Session s =null;
    try{
sessionFactory = new Configuration().configure("com\\xml\\hibernate.cfg.xml").buildSessionFactory();
s=sessionFactory.openSession();
}catch(HibernateException e){
System.out.println(e.getMessage());
  }finally{
  if(s!=null){
  s.close();
  }
  }
  return s;
 }

 public  List param(String[] args) throws Exception
{
List list = null;
Session s = getSession();
try{
DataInputStream ds=new DataInputStream(System.in);
System.out.println("*********************\n");
System.out.println("Enter the Degree to Search");
String first=ds.readLine();

Query query = s.createQuery("from Student stu where stu.degree = :deg order by stu.id ASC");
query.setString("deg",first);
query.setFirstResult(0);
query.setMaxResults(3);
list = query.list();
}catch(HibernateException e)
  {
    System.out.println(e.getMessage());
     }finally{
  if(s!=null){
  s.close();
  }
  }
  return list;
  }
}

---------------------------- Employee.hbm.xml ------------------------

<?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="com.ramsiscode.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>

----------------------------- hibernate.cfg.xml ------------------------

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="studentFactory">
       <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://10.68.238.96:3306/exampledb</property>
<property name="connection.username">cctns_app</property>
<property name="connection.password">cctns@123</property>
       <property name="connection.pool_size">5</property>
       <!-- SQL dialect -->
       <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
       <!-- Echo all executed SQL to stdout -->
       <property name="show_sql">true</property>
  <property name="hbm2ddl.auto">update</property>
<mapping resource="\com\\xml\\Student.hbm.xml"/>
<mapping resource="\com\\xml\\Employee.hbm.xml"/>

</session-factory>
</hibernate-configuration>

--------------------------- pagingEmp.jsp --------------------------


  <%@page import="com.ramsiscode.DAO" %>
  <%@page import="java.util.List" %>
  <%@page import="java.lang.Math" %>
  <%@page import="java.util.ArrayList" %>
  <%@ taglib uri='http://java.sun.com/jsp/jstl/core' prefix='c'%>
  <jsp:directive.page contentType="text/html; charset=UTF-8" />
 <link rel="stylesheet" type="text/css" href="css/screen.css" />
 <%
     int pageNumber=1;
     int footerPageLimit =4;
     String  prePage ="1";
     String nextPage ="1";
   
     int empListSize = 0;
     List sizeList =(List)  session.getAttribute("EmpList");
     if(sizeList!=null){
    empListSize = ((Integer) sizeList.size());
     }
     
     DAO dao = new DAO();
     Long   maxRow = dao.getMaxRow();
     System.out.println("maxRow size ------------"+maxRow);
     Integer pageLinks = Math.round(maxRow/8)+1;
     System.out.println("pageLinks ------------"+pageLinks);
     session.setAttribute( "pageLinks", pageLinks);

     
     if(request.getParameter("page") != null) {
       session.setAttribute("page", request.getParameter("page"));
       pageNumber = Integer.parseInt(request.getParameter("page"));
       
        Integer pageLinks_Session = (Integer) session.getAttribute("pageLinks");
        if(pageNumber>(pageLinks_Session)){
      pageNumber=1;
       }
       
        if(empListSize==0){
      pageNumber=1;
       }
       
       nextPage = (pageNumber +1) + "";
       prePage = (pageNumber -1) + "";
 
       String pages = request.getParameter("page");
      if(pages.equalsIgnoreCase("1")){
      prePage="1";
       }
     } else {
       session.setAttribute("page", "1");
     }
     
     /**********************************/
   
     session.setAttribute( "EmpList", dao.getData(pageNumber));

     
     /**********************************/

     
     System.out.println("empListSize : "+empListSize);
     if(empListSize==0){
    session.setAttribute("page", "1");
    nextPage ="1";
    prePage ="1";
     }
     
     int  prePages = (pageNumber)- 1;
     prePage =(String.valueOf(prePages));
     if(pageNumber==1){
    prePage ="1";
     }
     
     /**********************************/
     int startPage=  pageNumber;
     int endPage =  startPage+footerPageLimit-1;
     if(empListSize==0){
    startPage = 1;
    endPage = startPage+footerPageLimit-1;
     }
     /* if(pageNumber>=pageLinks){
    startPage=pageNumber;
    endPage=pageNumber;
     } */
     /**********************************/
     
     String myUrl = "pagingEmp.jsp?page=" + nextPage;
     String preUrl = "pagingEmp.jsp?page=" + prePage;
     System.out.println(myUrl);
 
     pageContext.setAttribute("myUrl", myUrl);
     pageContext.setAttribute("preUrl", preUrl);
%>
 <h2 align="center">Hibernate Pagination</h2>
<%--  <jsp:useBean id="EmpList" scope="request" type="java.util.List"></jsp:useBean> --%>

 <table>
   <tr>
     <th>Emp 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>
 </table>
 <BR/>
 <Table>
 <tr>
 <td colspan="2"><a href="${pageScope.preUrl}"><<&nbsp;previous</a>&nbsp;
     <c:forEach  var="i" begin="<%=startPage %>" end="<%=endPage %>">
        <a href="?page=${i}"> <c:out value="${i}"></c:out></a>
     </c:forEach>
     &nbsp; <a href="${pageScope.myUrl}">nextPage&nbsp;>></a></td>
 </tr>
 </Table>

Download Code

No comments:

Post a Comment