Example On Hibernate Pagination With Servlet In Eclipse

Let us see an example on hibernate pagination with servlet..

  • when response for request is too large [If we have 1000’s of records in the database] then instead of displaying all records at a time on browser  we can display the response page by page manner using pagination mechanism
  • In pagination, initially one page response will be displayed and we will get links for getting the next pages response
  • In this servelt & hibernate integration, we are going to display  4 records or 4 objects of products using hibernate for selecting the data and we will get links to display the records of the next pages

 

Regarding Logic  In Order To Get pagination

  • The servlet accepts pageIndex parameter and if the parameter is passed then servlet takes the given number as pageIndex, otherwise the servlet will takes the pageIndex as one [ 1  ]
  • Servlet uses Criteria API and the pagination methods of Criteria for loading the records (objects) related to that particular page, and servlet display those records on the browser
  • In servlet we use Criteria with projection for finding the total number of records available in the table, and we store that number into the variable
  • We will find out the number of hyperlinks required by dividing the total number of records with records per page
  • we need to use a loop in order to display the links on the browser, while creating each link,  we use the <a href  /> to servlet url pattern [Hiper reference] and by passing that page nomber as value for pageIndex parameter
  • Hibernate Pagination Example In Eclipse

    Mates, let see one real time example on this hibernate pagination with servlet
    files required…

  • Pagination.java
  • Product.java
  • Product.hbm.xml
  • hibernate.cfg.xml
  • web.xml
  • Let us see the directory structure  in the Eclipse ..

    Servlet is j2ee related application, so just create one application newly unlike previous normal java programs

    Open eclipse –> New –>  Dynamic Web Project

     Note:

  • src folder contains all *.java files
  • build folder contains all *.class files in side classes folder
  • Hibernate related xml’s hibernate.cfg.xml, mapping files should be in classes folder only
  • product.java

    123456789101112131415161718192021222324252627282930313233public class Product{
    
    	private int productId;
    	private String proName;
    	private double price;
    
    	public void setProductId(int productId)
    	{
    	    this.productId = productId;
    	}
    	public int getProductId()
    	{
    	    return productId;
    	}
    
    	public void setProName(String proName)
    	{
    	    this.proName = proName;
    	}
    	public String getProName()
    	{
    	    return proName;
    	}
    
    	public void setPrice(double price)
    	{
    	    this.price = price;
    	}
    	public double getPrice()
    	{
    	    return price;
    	}
    }

    Product.xml

    1234567891011121314<?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.java4s.hservlet.pagination.Product" table="products">
    
    <id name="productId" column="pid"  />
    <property name="proName" column="pname" length="10"/>
    <property name="price"/>
    
    </class>
    </hibernate-mapping>

    hibernate.cfg.xml

    1234567891011121314151617181920<?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:@www.java4s.com:1521:XE</property>
    <property name="connection.username">system</property>
    <property name="connection.password">admin</property>
    
    <property name="dialect">org.hibernate.dialect.OracleDialect</property>
    <property name="show_sql">true</property>
    <property name="hbm2ddl.auto">update</property>
    
    <mapping resource="Product.hbm.xml"></mapping>
    </session-factory>
    </hibernate-configuration>

    Pagination.java

    123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Iterator;
    import java.util.List;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServlet;
    
    import org.hibernate.Criteria;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.criterion.Projections;
    
    public class Pagination extends HttpServlet
    {
    
    SessionFactory factory;
    
    

    //init method started

    public void init(ServletConfig config)throws ServletException { factory = new Configuration().configure().buildSessionFactory(); System.out.println("Factory has been created...."); }

    //init method end

    //service method start

    public void service(ServletRequest req, ServletResponse res) throws ServletException,IOException { int pageIndex = 0; int totalNumberOfRecords = 0; int numberOfRecordsPerPage = 4; String sPageIndex = req.getParameter("pageIndex"); if(sPageIndex ==null) { pageIndex = 1; }else { pageIndex = Integer.parseInt(sPageIndex); } Session ses = factory.openSession(); int s = (pageIndex*numberOfRecordsPerPage) -numberOfRecordsPerPage; Criteria crit = ses.createCriteria(Product.class); crit.setFirstResult(s); crit.setMaxResults(numberOfRecordsPerPage); List l = crit.list(); Iterator it = l.iterator(); PrintWriter pw = res.getWriter(); pw.println("<table border=1>"); pw.println("<tr>"); pw.println("<th>PID</th><th>PNAME</th><th>PRICE</th>"); pw.println("</tr>"); while(it.hasNext()) { Product p = (Product)it.next(); pw.println("<tr>"); pw.println("<td>"+p.getProductId()+"</td>"); pw.println("<td>"+p.getProName()+"</td>"); pw.println("<td>"+p.getPrice()+"</td>"); pw.println("</tr>"); } pw.println("<table>"); Criteria crit1 = ses.createCriteria(Product.class); crit1.setProjection(Projections.rowCount()); List l1=crit1.list(); // pw.println(l1.size()); //returns 1, as list() is used to execute the query if true will returns 1 Iterator it1 = l1.iterator(); if(it1.hasNext()) { Object o=it1.next(); totalNumberOfRecords = Integer.parseInt(o.toString()); } int noOfPages = totalNumberOfRecords/numberOfRecordsPerPage; if(totalNumberOfRecords > (noOfPages * numberOfRecordsPerPage)) { noOfPages = noOfPages + 1; } for(int i=1;i<=noOfPages;i++) {

    String myurl = "ind?pageIndex="+i;

    pw.println("<a href="+myurl+">"+i+"</a>"); } ses.close(); pw.close(); }

    //service method end

    //destroy method start

    public void destroy() { factory.close(); }

    //destroy end

    }

    Note:

  • We must create the SessionFactory object in the init() only, as it is the heavy weight one
  • and nothing to explain, just read slowly. If you got struck at any point just fire a question in our forum, and see line number 101,  ind?pageIndex (ind is my url pattern)
  • web.xml

    1234567891011<web-app>
    <servlet>
    <servlet-name>dummyName</servlet-name>
    <servlet-class>com.java4s.hservlet.pagination.Pagination</servlet-class>
    </servlet>
    
    <servlet-mapping>
    <servlet-name>dummyName</servlet-name>
    <url-pattern>/ind</url-pattern>
    </servlet-mapping>
    </web-app>

    Output in eclipse:

    Right click on the project root — > run –> Run on Server

Related Articles

post a comment