Newsletter

Example On Hibernate Pagination With Servlet In Eclipse

Hibernate » on Jul 21, 2011 { 14 Comments } By Sivateja

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

public 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

<?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

<?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

import 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

<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

 

 

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

14 Responses to “Example On Hibernate Pagination With Servlet In Eclipse”
  1. Robin says:

    while i am running the program……my Pagination class is not found……plz help me

  2. Java4s says:

    @Robin

    I have tested the application and its working fine from my end, make sure you followed the the same steps, and again download the application –> import into your eclipse and test again.

    Let me know the exception you are getting, if you still have any problem.

  3. siva says:

    Really very helpful….:)

  4. tapan says:

    what does setFirstResult in criteria does

  5. Hari says:

    I am thrilled with ur logic.. Thanks for ur information:)

  6. while im creating database in oracle its giving error…. error is create database is falied… database is already mounted… plz give me solution on this….

  7. shaziya says:

    I am getting number format exception
    For input string: “com.exilant.beans.Product@70dbdc4b”
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)

    which is this line

    String sPageIndex = request.getParameter(“pageIndex”);

  8. Anand says:

    Hi,
    This is awesome example but what if many clients connects?
    What about threading synchronization issues?
    Can I use HttpSession object to hold SessionFactory reference?
    Or can I use synchronized block?
    In dotnet for such scenarios DataTable are used which use disconnected architecture, so there will be no connection with the database. What happens in case of Hibernate? is it caching the while data in memory or fetch data from database every time? Can u please share?
    Please comment.
    Thanks.

  9. Bibek says:

    After downloading and importing it says 404 error
    please help me

  10. sandash says:

    thanks, i want same logic with Previous and next buttons

  11. mani says:

    i can’t understand this concept . so i kindly request u to explain in detail and how to work this?

  12. Chitty says:

    Hi Siva,

    Please let me know about pagination,If we dont know how many records are there in the database then how to achieve the pagination?

  13. Fadtare Mukteshwar says:

    Pagination.java line no:-36
    //String sPageIndex = req.getParameter("pageIndex");
    above line I could not understand from where have u taken,and what will be the value in that.

  14. swathi says:

    i am getting Product.hbm.xml not found

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.