
- Hibernate - Home
- ORM - Overview
- Hibernate - Overview
- Hibernate - Architecture
- Hibernate - Environment
- Hibernate - Configuration
- Hibernate - Sessions
- Hibernate - Persistent Class
- Hibernate - Mapping Files
- Hibernate - Mapping Types
- Hibernate - Examples
- Hibernate - O/R Mappings
- Hibernate - Cascade Types
- Hibernate - Annotations
- Hibernate - Query Language
- Hibernate - Criteria Queries
- Hibernate - Native SQL
- Hibernate - Caching
- Hibernate - Entity Lifecycle
- Hibernate - Batch Processing
- Hibernate - Interceptors
- Hibernate - ID Generator
- Hibernate - Saving Image
- Hibernate - log4j Integration
- Hibernate - Spring Integration
- Hibernate - Struts 2 Integration
- Hibernate - Web Application
- Mapping Table Examples
- Hibernate - Table Per Hiearchy
- Hibernate - Table Per Concrete Class
- Hibernate - Table Per Subclass
Hibernate - Example Web Application
In this tutorial, we will build a sample web application. It is a simple application with 2 jsp's, index.jsp and showResults.jsp. User will enter a Student ID and hit the button 'Search'. The showResults.jsp will display Student information based on the Student ID.
Create UI Pages
Let's create following jsp pages to be used in this web application.
index.jsp
<form action="showResults.jsp" method="post"> <center>Student id:<input type="text" name="StudentId"/><br><br/> <input type="submit" value="Search"/></center> </form>
showResults.jsp
<%@ page import="com.tutorialspoint.webhibernate.*" %> <% String as = request.getParameter("StudentId"); System.out.println("StudentId: " + as); if(as.equals("")){ out.print("Sorry, you have not entered Student Id"); } int idr = Integer.parseInt(as); Student st1 = StudentDAO.getStudent(idr); %> <body> <table border="1" align="center"> <thead><tr><td>StudentID</td><td>First Name</td><td>Last Name</td><td>Dept<td></tr></thead> <tr><td><%= st1.getStudentid() %></td><td><%= st1.getfName()%></td><td><%= st1.getlName() %></td><td><%= st1.getDept() %></td></tr> </table> </body>
Create Database Table
Let's create a Students table and insert data using following sql queries −
create table students( StudentID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), Dept varchar(255), primary key(StudentID) ); insert into students values (1000, 'Agarwal', 'Bonny', '12 Southern Ave', 'Mathematics') (1001, 'Pandey', 'Amit', ' 8 Ganesh Chandra Rd. ', 'Physics') (1002, 'Kumar', 'Kalyan', '42 Brick Rd., Alipur', 'English');
Create Hibernate Configuration File
Now create a hibernate configuration file for database and other details.
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hbm2ddl.auto">update</property> <property name="dialect">org.hibernate.dialect.MySQL8Dialect</property> <property name="connection.url">jdbc:mysql://localhost/TUTORIALSPOINT</property> <property name="connection.username">root</property> <property name="connection.password">guest123</property> <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property> <mapping resource="student.hbm.xml"/> </session-factory> </hibernate-configuration>
Create Mapping Configuration File
Now create a mapping file that instructs Hibernate how to map the Student object to the database table.
student.hbm.xml
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.tutorialspoint.webhibernate.Student" table="students"> <id name="studentid"> <generator class="increment"></generator> </id> <property name="fName" column="firstname"></property> <property name="lName" column="lastname"></property> <property name="dept" column="dept"></property> </class> </hibernate-mapping>
Create Java Classes
Now let's create the Student POJO class and a DAO class to persist the Student object:
Student.java
package com.tutorialspoint.webhibernate; public class Student { private int studentid; private String fName; private String lName; private String dept; public Student() {} public Student(int i) { this.studentid = i; } public Student getStudentForId(int j) { Student s1 = StudentDAO.getStudent(studentid); return s1; } public int getStudentid() { return studentid; } public void setStudentid(int studID) { studentid = studID; } public String getfName() { return fName; } public void setfName(String fName) { this.fName = fName; } public String getlName() { return lName; } public void setlName(String lName) { this.lName = lName; } public String getDept() { return dept; } public void setDept(String dept) { this.dept = dept; } }
StudentDAO.java
package com.tutorialspoint.webhibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.query.Query; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import java.util.List; import java.util.Iterator; public class StudentDAO { public static Student getStudent(int i) { StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build(); Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build(); SessionFactory factory=meta.getSessionFactoryBuilder().build(); Session session=factory.openSession(); Transaction tx = session.beginTransaction(); String hql = " from Student where studentid = :student_id "; Query<?> query = session.createQuery(hql, Student.class); query.setParameter("student_id", i); System.out.println("student_id: " + i); List<Student> k = (List<Student>) query.getResultList(); System.out.println("List size: " + k.size()); tx.commit(); session.close(); Student st = new Student(1); for (Iterator<?> iterator = k.iterator(); iterator.hasNext();){ st = (Student) iterator.next(); } return st; } }
Steps to deploy Web Application
We're using Tomcat to deploy this web application. Once Tomcat is installed, we're assuming TOMCAT_HOME environment variable represents the tomcat installation directory.
Create a directory called WebHibernate under TOMCAT_HOME/webapps directory.
Under this directory(TOMCAT_HOME/webapps), place index.jsp, showResults.jsp
Create a directory, WEB-INF in the same directory (TOMCAT_HOME/webapps).
-
Under WEB-INF, create a new file web.xml and add the following:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
Create a directory lib under WEB-INF and place all the dependencies.
Create directory structure under WEB-INF/classes/com/tutorialspoint/webhibernate/ and place Student.class, StudentDAO.class
Start Tomcat
Output
Open browser, type URL: http://localhost:8080/WebHibernate .Your index page is going to look like this:

Enter 1000 for Student Id. The results page looks like this:
