Hibernate JSP

In this section, you will learn about Hibernate with JSP using simple pagination example.

Hibernate JSP

Hibernate JSP

In this section, you will learn about Hibernate with JSP using simple pagination example.

In the below example, we will describe you how to do pagination using simple JSP and Hibernate.

The project hierarchy and the jar files used is given below :

The SQL query used to create table contact is given below:

CREATE TABLE `contacts` ( 
`id` int(11) NOT NULL auto_increment, 
`firstname` varchar(30) default NULL, 
`lastname` varchar(30) default NULL, 
`cell_no` varchar(15) default NULL, 
`email_id` varchar(30) default NULL, 
`website` varchar(150) default NULL, 
`birthdate` date default NULL, 
`created` timestamp NOT NULL default CURRENT_TIMESTAMP, 
PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 

CODE

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>JspHibernate</display-name>
<welcome-file-list>
<welcome-file>contact.jsp</welcome-file>
</welcome-file-list>
</web-app>

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.10.13:3306/ankdb
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>

<mapping class="devmanuals.model.Contact" />

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

Contact.java

package roseindia.model;

import java.io.Serializable;
import java.sql.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="contacts")
public class Contact implements Serializable{

private static final long serialVersionUID = -8767337896773261247L;

private Long id;
private String firstName;
private String lastName;
private String emailId;
private String cellNo;
private Date birthDate;
private String website;
private Date created;

@Id
@GeneratedValue
@Column(name="id")
public Long getId() {
return id;
}
@Column(name="firstname")
public String getFirstName() {
return firstName;
}
@Column(name="lastname")
public String getLastName() {
return lastName;
}
@Column(name="email_id")
public String getEmailId() {
return emailId;
}
@Column(name="cell_no")
public String getCellNo() {
return cellNo;
}
@Column(name="birthdate")
public Date getBirthDate() {
return birthDate;
}
@Column(name="website")
public String getWebsite() {
return website;
}
@Column(name="created")
public Date getCreated() {
return created;
}
public void setId(Long id) {
this.id = id;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public void setCellNo(String cellNo) {
this.cellNo = cellNo;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public void setCreated(Date created) {
this.created = created;
}
public void setWebsite(String website) {
this.website = website;
}
}

DAO.java

package roseindia.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class DAO {
private static SessionFactory sf;
private static ServiceRegistry serviceRegistry;
private static int pageSize = 3;
public static List getData(int pageNumber) {
try {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
sf = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
} 
Session session = sf.openSession();
List result = null;
try {
session.beginTransaction();
Query query = session.createQuery("from Contact");
query = query.setFirstResult(pageSize * (pageNumber - 1));
query.setMaxResults(pageSize);
result = query.list();
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}

contact.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@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;
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", roseindia.dao.DAO.getData(pageNumber));
System.out.println(((java.util.List)session.getAttribute("EmpList")).size());
String myUrl = "contact.jsp?page=" + nextPage;
System.out.println(myUrl);
pageContext.setAttribute("myUrl", myUrl);
%>
<h2>Showing Table Records</h2>
<jsp:useBean id="EmpList" scope="session" type="java.util.List"></jsp:useBean>
<table border="1">
<tr>
<th>Id</th>
<th>Fname</th>
<th>Lname</th>
<th>Email</th>
<th>Mobile</th>
<th>Date</th>
<th>Web Site</th>
<th>Creation Date</th>

</tr>
<c:forEach items="${EmpList}" var="emp" begin="0" end="10">
<tr>
<td><c:out value="${emp.id}"></c:out>&nbsp;&nbsp;&nbsp;</td>
<td><c:out value="${emp.firstName}"></c:out></td>
<td><c:out value="${emp.lastName}"></c:out></td>
<td><c:out value="${emp.emailId}"></c:out></td>
<td><c:out value="${emp.cellNo}"></c:out></td>
<td><c:out value="${emp.birthDate}"></c:out></td>
<td><c:out value="${emp.website}"></c:out></td>
<td><c:out value="${emp.created}"></c:out></td>
</tr>
</c:forEach>

<tr>
<td colspan="2"></td>
<td colspan="2"><a href="${pageScope.myUrl}">Next Page</a></td>
</tr>
</table>

OUTPUT

After executing the above code, you will get the following page as output in the browser  :

Download Source Code