Hibernate
Hibernate
JDBC refers to the Java Database Connectivity. It provides java API that allows Java
programs to access database management systems (relational database). The JDBC API
consists of a set of interfaces and classes which enables java programs to execute SQL
statements. Interfaces and classes in JDBC API are written in java.
Why Object-relational mapping (ORM)?
As we discussed JDBC provides a way for Java programs to communicate with the relational
database. Java follows the object model and represents the data in the form of interconnected
graph of objects whereas relational database represents the data in the tabular form. This
creates a mismatch between the object model and the relational database. ORM resolve this
mismatch problem.
What is ORM?
ORM refers to the Object-Relational Mapping. It is a programming technique for converting
data between incompatible type systems like relational databases and object oriented
programming languages like java.
Commonly used Java ORM Frameworks:
Hibernate.
Enterprise JavaBeans Entity Beans
Spring DAO
Hibernate framework is an object-relational mapping library for the Java language. It is an
open source persistent framework started by Gavin King in 2001. It provides the facility to
map the java classes to relational database tables and Java data types to SQL data types.
Note: Hibernate framework acts as an intermediate layer between java objects and relational
database.
Diagram:
Advantages of Hibernate framework:
Hibernate framework is an open source framework.
Hibernate framework is a high performance framework because of its internal cache.
It maps java classes to database tables using XML files and if any change is made to the
database than we have to change these XML files only.
It provides a database independent query language HQL (Hibernate Query Language).
It provides the facility to create tables from your java application.
No application server is required.
Hibernate architecture
Hibernate architecture consist of hibernate core components and use existing Java APIs. It uses JDBC
API for common functionality to communicate with relational database and JNDI and JTA to
integrate hibernate to the java application servers.
Diagram:
Core Components of Hibernate architecture:
Configuration object:
The configuration object consist the configuration file used by the hibernate. It mainly consist the
information about database connection (hibernate.cfg.xml) and class mapping (.hbm.xml).
Configuration object is used to create the object of SessionFactory.
SessionFactory object:
The SessionFactory object is created from the Configuration object. It is thread-safe object and used
by all threads of the application. It acts as a factory for session objects and client for
ConnectionProvider. It maintains the second level cache of the data.
Session object:
The session object is created from the SessionFactory object. It acts as a factory for Transaction,
Query and Criteria. Session objects are not thread-safe. It maintains the first level cache.
Transaction object:
The Transaction object is created from Session object. A transaction object represents an atomic unit
of work.
Query object:
The Query object is created from Session object. It uses SQL and HQL to perform database
operations.
Criteria object:
The Criteria object is created from the Session object. It is used to define and execute the object
oriented criteria queries.
Hibernate configuration file
As we discussed that hibernate works as an intermediate layer between java application and relational
database. So hibernate needs some configuration setting related to the database and other parameters
like mapping files. A hibernate configuration file contains all such information.
A hibernate configuration file mainly contains three types of information:
Connection Properties related to the database.
Hibernate Properties related to hibernate behaviour.
Mapping files entries related to the mapping of a POJO class and a database table.
How to create a hibernate configuration file?
We can create a hibernate configuration file either by using java properties file known as
hibernate.properties or by using an xml file known as hibernate.cfg.xml. The hibernate.cfg.xml file is
used mostly.
Note: No. of hibernate configuration files in an application is dependence upon the no. of database
uses. No. of hibernate configuration files are equals to the no. of database uses.
Syntax:
<hibernate-configuration>
<session-factory>
// Connection Properties
<property name="connection.driver_class">driverClassName</property>
<property name="connection.url">jdbcConnectionURL</property>
<property name="connection.user">databaseUsername</property>
<property name="connection.password">databasePassword</property>
// Hibernate Properties
<property name="show_sql">true/false</property>
<property name="dialet">databaseDialetClass</property>
<property name="hbm2ddl.auto">like create/update</property>
// Mapping files entries
<mapping resource="mappingFile1.xml" />
<mapping resource="mappingFile2.xml" />
</session-factory>
</hibernate-configuration>
Persistent class
Persistent classes are those java classes whose objects have to be stored in the database tables. They
should follow some simple rules of Plain Old Java Object programming model (POJO).
Some rules that should be, not must be followed by a persistence class.
A persistence class should have a default constructor.
A persistence class should have an id to uniquely identify the class objects.
All attributes should be declared private.
Public getter and setter methods should be defined to access the class attributes.
Example:
Student.java
/**
* This class represents a persistent class for Student.
* @author w3spoint
*/
public class Student {
//data members
private int studentId;
private String firstName;
private String lastName;
private String className;
private String rollNo;
private int age;
//no-argument constructor
public Student(){
}
//getter and setter methods
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getClassName() {
return className;
}
public void setClassName(String className)
{
this.className = className;
}
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Object states in Hibernate
A persistent class object can be in one of the following three states:
Transient.
Persistent.
Detached.
1. Transient:
A persistent class object is said to be in transient state if it is not associated with hibernate session.
2. Persistent:
A persistent class object is said to be in transient state if it is associated with hibernate session.
3. Detached:
A persistent object becomes detached object when hibernate session is closed.
Example:
//Create the student object. Student object is in trabsient state here.
Student student = new Student();
//Setting the object properties.
student.setFirstName("Vivek");
student.setLastName("Solenki");
student.setClassName("MCA final");
student.setRollNo("MCA/07/70");
student.setAge(27);
//Get the session object.
Session session = HibernateUtil.getSessionFactory().openSession();
//Start hibernate transaction.
session.beginTransaction();
//Persist the student object. Student object is in persistence state here.
session.save(student);
//Commit hibernate transaction.
session.getTransaction().commit();
//Close the hibernate session.
session.close();
// Student object is in detached state here
//if we want to do any operation on it.
Hibernate mapping file
Hibernate mapping file is used by hibernate framework to get the information about the mapping of a
POJO class and a database table.
It mainly contains the following mapping information:
Mapping information of a POJO class name to a database table name.
Mapping information of POJO class properties to database table columns.
Elements of the Hibernate mapping file:
hibernate-mapping: It is the root element.
Class: It defines the mapping of a POJO class to a database table.
Id: It defines the unique key attribute or primary key of the table.
generator: It is the sub element of the id element. It is used to automatically generate the id.
property: It is used to define the mapping of a POJO class property to database table column.
Syntax:
<hibernate-mapping>
<class name="POJO class name" table="table name in database">
<id name="propertyName" column="columnName" type="propertyType" >
<generator class="generatorClass"/>
</id>
<property name="propertyName1" column="colName1" type="propertyType " />
<property name="propertyName2" column="colName2" type="propertyType " />
….
</class>
</hibernate-mapping>
Hibernate transaction management
Transaction:
A transaction is a sequence of operation which works as an atomic unit. A transaction only completes
if all the operations completed successfully. A transaction has the Atomicity, Consistency, Isolation
and Durability properties (ACID).
Transaction interface:
Transaction interface provides the facility to define the units of work or transactions. A transaction is
associated with a session. We have to call beginTransaction()method of Session to start a transaction
(Session.beginTransaction()).
Commonly used methods of Transaction interface:
1. begin(): It starts a new transaction.
Syntax:
public void begin() throws HibernateException
2. commit(): It ends the transaction and flush the associated session.
Syntax:
public void commit() throws HibernateException
3. rollback(): It roll back the current transaction.
Syntax:
public void rollback()throws HibernateException
4. setTimeout(int seconds): It set the transaction timeout for any transaction started by a subsequent
call to begin() on this instance.
Syntax:
public void setTimeout(int seconds) throws HibernateException
5. isActive(): It checks that is this transaction still active or not.
Syntax:
public boolean isActive()throws HibernateException
6. wasRolledBack(): It checks that is this transaction roll backed successfully or not.
Syntax:
public boolean wasRolledBack()throws HibernateException
7. wasCommitted():It checks that is this transaction committed successfully or not.
Syntax:
public boolean wasCommitted()throws HibernateException
8. registerSynchronization(Synchronization synchronization): It register a user synchronization
callback for this transaction.
Syntax:
public boolean registerSynchronization(Synchronization synchronization)throws HibernateException
Example:
Transaction tx = null;
//Get the session object.
Session session =
HibernateUtil.getSessionFactory().openSession();
try{
tx = session.beginTransaction();
//Perform some operation here
tx.commit();
}catch (HibernateException e) {
if(tx!=null){
tx.rollback();
}
e.printStackTrace();
}finally {
session.close();
}
Hibernate example using xml mapping
As we discussed primary things like hibernate architecture, object states, configuration files, mapping
files, transaction management to make a hibernate program. Let us start with a simple hibernate
program to save a student class object into the database.
Example:
Student.java
/**
* This class represents a persistent class for Student.
* @author w3spoint
*/
public class Student {
//data members
private int studentId;
private String firstName;
private String lastName;
private String className;
private String rollNo;
private int age;
//no-argument constructor
public Student(){
}
//getter and setter methods
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getClassName() {
return className;
}
public void setClassName(String className)
{
this.className = className;
}
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">
org.hibernate.dialect.OracleDialect
</property>
<property name="connection.url">
jdbc:oracle:thin:@localhost:1521:XE
</property>
<property name="connection.username">
system
</property>
<property name="connection.password">
oracle
</property>
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="hbm2ddl.auto">
update
</property>
<property name="show_sql">
true
</property>
<mapping resource="student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
student.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping SYSTEM
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.w3spoint.business.Student" table="Student">
<id name="studentId" type="int" column="Student_Id">
<generator class="native"></generator>
</id>
<property name="firstName" column="First_Name"
type="string"/>
<property name="lastName" column="Last_Name" type="string"/>
<property name="className" column="Class" type="string"/>
<property name="rollNo" column="RollNo" type="string"/>
<property name="age" column="Age" type="int"/>
</class>
</hibernate-mapping>
HibernateUtil.java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* This is a utility class for getting the hibernate session
object.
* @author w3spoint
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory =
buildSessionFactory();
private static SessionFactory buildSessionFactory() {
SessionFactory sessionFactory = null;
try {
//Create the configuration object.
Configuration configuration = new Configuration();
//Initialize the configuration object
//with the configuration file data
configuration.configure("hibernate.cfg.xml");
// Get the SessionFactory object from configuration.
sessionFactory = configuration.buildSessionFactory();
}
catch (Exception e) {
e.printStackTrace();
}
return sessionFactory;
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
HibernateTest.java
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.w3spoint.persistence.HibernateUtil;
/**
* This class is used for the hibernate operations.
* @author w3spoint
*/
public class HibernateTest {
public static void main(String args[]){
//Create the student object.
Student student = new Student();
//Setting the object properties.
student.setFirstName("Vivek");
student.setLastName("Solenki");
student.setClassName("MCA final");
student.setRollNo("MCA/07/70");
student.setAge(27);
Transaction tx = null;
//Get the session object.
Session session =
HibernateUtil.getSessionFactory().openSession();
try{
//Start hibernate session.
tx = session.beginTransaction();
//Insert a new student record in the database.
session.save(student);
//Commit hibernate transaction if no exception
occurs.
tx.commit();
}catch (HibernateException e) {
if(tx!=null){
//Roll back if any exception occurs.
tx.rollback();
}
e.printStackTrace();
}finally {
//Close hibernate session.
session.close();
}
}
}
Output:
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into Student (First_Name, Last_Name,
Class,
RollNo, Age, Student_Id) values (?, ?, ?, ?, ?, ?)
Saved Successfully.
below image.
Hibernate Maven Dependencies
Our final pom.xml file contains dependencies for Hibernate and MySQL driver. Hibernate uses JBoss
logging and it automatically gets added as transitive dependencies.
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-
instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-
4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.journaldev.hibernate</groupId>
<artifactId>HibernateOneToManyMapping</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.5</version>
</dependency>
</dependencies>
</project>
Note that I am using latest Hibernate version 4.3.5.Final and MySQL driver version based on my
database installation.
Hibernate One To Many Mapping Model Classes
For our tables Cart and Items, we have model classes to reflect them. Cart.java
package com.journaldev.hibernate.model;
import java.util.Set;
}
I am using Set of Items, so that every record is unique. We can also use List or Array for one to many
mapping in hibernate. Items.java
package com.journaldev.hibernate.model;
}
Items have many to one relationship to Cart, so we don’t need to have Collection for Cart object.
Hibernate SessionFactory Utility Class
We have a utility class for creating Hibernate SessionFactory. HibernateUtil.java
package com.journaldev.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
return sessionFactory;
}
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="cart.hbm.xml"/>
<mapping resource="items.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Hibernate One To Many Mapping Example - XML Configuration
This is the most important part of tutorial, let’s see how we have to map both Cart and Items classes
for one to many mapping in hibernate. cart.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"https://hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.journaldev.hibernate.model">
<class name="Cart" table="CART" >
<id name="id" type="long">
<column name="cart_id" />
<generator class="identity" />
</id>
<property name="total" type="double">
<column name="total" />
</property>
<property name="name" type="string">
<column name="name" />
</property>
<set name="items" table="ITEMS" fetch="select">
<key>
<column name="cart_id" not-null="true"></column>
</key>
<one-to-many class="Items"/>
</set>
</class>
</hibernate-mapping>
The important part is the set element and one-to-many element inside it. Notice that we are providing
key to be used for one to many mapping i.e cart_id. items.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"https://hibernate.org/dtd/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.journaldev.hibernate.model">
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.journaldev.hibernate.model.Cart;
import com.journaldev.hibernate.model.Items;
import com.journaldev.hibernate.util.HibernateUtil;
cart.setItems(itemsSet);
cart.setTotal(10*1 + 20*2);
//Commit transaction
tx.commit();
System.out.println("Cart ID="+cart.getId());
}catch(Exception e){
System.out.println("Exception occured. "+e.getMessage());
e.printStackTrace();
}finally{
if(!sessionFactory.isClosed()){
System.out.println("Closing SessionFactory");
sessionFactory.close();
}
}
}
}
Notice that we need to save both Cart and Items objects one by one. Hibernate will take care of
updating the foreign keys in Items table. When we execute above program, we get following output.
Hibernate Configuration loaded
Hibernate serviceRegistry created
Session created
Hibernate: insert into CART (total, name) values (?, ?)
Hibernate: insert into ITEMS (item_id, item_total, quantity, cart_id) values (?, ?, ?, ?)
Hibernate: insert into ITEMS (item_id, item_total, quantity, cart_id) values (?, ?, ?, ?)
Hibernate: update ITEMS set cart_id=? where id=?
Hibernate: update ITEMS set cart_id=? where id=?
Cart ID=6
Closing SessionFactory
Notice that Hibernate is using Update query to set the cart_id in ITEMS table.
Hibernate One To Many Mapping Annotation
Now that we have seen how to implement One To Many mapping in Hibernate using XML based
configurations, let’s see how we can do the same thing using JPA annotations.
Hibernate One To Many Mapping Example Annotation
Hibernate configuration file is almost same, except that mapping element changes because we are
using Classes for hibernate one to many mapping using annotation. hibernate-annotation.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">pankaj123</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/TestDB</property>
<property name="hibernate.connection.username">pankaj</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<mapping class="com.journaldev.hibernate.model.Cart1"/>
<mapping class="com.journaldev.hibernate.model.Items1"/>
</session-factory>
</hibernate-configuration>
Hibernate SessionFactory Utility Class
SessionFactory utility class is almost same, we just need to use the new hibernate configuration file.
HibernateAnnotationUtil.java
package com.journaldev.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateAnnotationUtil {
return sessionFactory;
}
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="CART")
public class Cart1 {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="cart_id")
private long id;
@Column(name="total")
private double total;
@Column(name="name")
private String name;
@OneToMany(mappedBy="cart1")
private Set<Items1> items1;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="ITEMS")
public class Items1 {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private long id;
@Column(name="item_id")
private String itemId;
@Column(name="item_total")
private double itemTotal;
@Column(name="quantity")
private int quantity;
@ManyToOne
@JoinColumn(name="cart_id", nullable=false)
private Cart1 cart1;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.journaldev.hibernate.model.Cart1;
import com.journaldev.hibernate.model.Items1;
import com.journaldev.hibernate.util.HibernateAnnotationUtil;
cart.setItems1(itemsSet);
cart.setTotal(10*1 + 20*2);
}catch(Exception e){
System.out.println("Exception occured. "+e.getMessage());
e.printStackTrace();
}finally{
if(!sessionFactory.isClosed()){
System.out.println("Closing SessionFactory");
sessionFactory.close();
}
}
}
}
When we execute above hibernate one to many mapping annotation example test program, we get
following output.
Hibernate Annotation Configuration loaded
Hibernate Annotation serviceRegistry created
Session created
Hibernate: insert into CART (name, total) values (?, ?)
Hibernate: insert into ITEMS (cart_id, item_id, item_total, quantity) values (?, ?, ?, ?)
Hibernate: insert into ITEMS (cart_id, item_id, item_total, quantity) values (?, ?, ?, ?)
Cart1 ID=7
item1 ID=9, Foreign Key Cart ID=7
item2 ID=10, Foreign Key Cart ID=7
Closing SessionFactory
That’s all for hibernate one to many mapping, download the sample project from below link and do
some more experiments.
Project Structure :
Create a simple java project in Eclipse, and add hibernate related jar files to the classpath of the
project. The final project structure is given below.
One-to-Many Mapping
Hibernate Tutorial
Hibernate Basics
Hibernate Inheritance Mapping
Hibernate Query Language (HQL)
Composite Primary Keys In Hibernate
package com.jwt.hibernate;
}
Create Hibernate Mapping File :
Create student.hbm.xml file to map the Student class with the database tables.
?
Create the Hibernate configuration file (hibernate.cfg.xml) to specify database type, connection
details and the mapping files:
hibernate.cfg.xml
?
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/jwt</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">mukesh</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update </property>
<mapping resource="com/jwt/hibernate/student.hbm.xml" />
</session-factory>
</hibernate-configuration>
Create the Hibernate configuration file (hibernate.cfg.xml) to specify database type, connection
details and the mapping files:
InsertData.java
?
package com.jwt.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
Transaction tx = session.beginTransaction();
session.save(student);
session.save(student1);
System.out.println("Object saved successfully.....!!");
tx.commit();
session.close();
factory.close();
}
}
package com.jwt.hibernate;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
tx.commit();
session.close();
factory.close();
}
}
package com.jwt.hibernate;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
// Update Employee
Query query = session
.createQuery("update Student set name= :name where id= :id");
query.setParameter("name", "Amit Raj");
query.setLong("id", 1);
int result = query.executeUpdate();
System.out.println("Student data Update Status=" + result);
tx.commit();
session.close();
factory.close();
}
Hibernate Query Language (HQL) Example Tutorial
March 15, 2015 by Mukesh Kumar at 3:47 pm
Hibernate Framework comes with a powerful object-oriented query language – Hibernate Query
Language (HQL). Hibernate Query Language is same as SQL (Structured Query Language) but
instead of tables it deals with classes and instead of columns it deals with properties or class
attributes.
HQL queries are database independent queries because HQL queries internally converted into
database specific SQL queries using Dialect class mentioned in hibernate-cfg.xml file.
Advantage of HQL
Database independent
Easy to learn for Java Programmer
HQL fully supports polymorphic queries. That is, along with the object to be returned as a query
result, all child objects (objects of subclasses) of the given object shall be returned.
Hibernate Tutorial
Hibernate Basics
Hibernate Inheritance Mapping
Hibernate Query Language (HQL)
Composite Primary Keys In Hibernate
HQL Syntax
Most of HQL's syntax and features are very similar to SQL. An HQL query may consist of following
elements:
Clauses
Aggregate functions
Subqueries
Clauses
from
as
select
where
order by
group by
update
delete
insert
from clause :
From clause is the most important hibernate query. This clause is used to load a complete persistent
object into memory.
Syntax:-
?
as clause :
Syntax:-
?
The "as" keyword is optional—you can also specify the alias directly after the class name, as
mentioned below:
?
from Employee e
select clause :
The select clause is used to obtain few properties of objects instead of the complete object.
Syntax:-
?
where clause :
The where clause is used to fetch the specific objects from the database.
Syntax:-
?
Order by clause :
This clause is used to sort our HQL query’s results. We can arrange the result by any property on the
objects in the result set either ascending (ASC) or descending (DESC) order.
Syntax:-
?
String hql = "FROM Person P WHERE P.id > 10 ORDER BY P.salary DESC";
Query query = session.createQuery(hql);
group by clause :
Group by clause Takes information from database ant group it based on a value of an attribute and
typically, use the result to include an aggregate value. It returns aggregate values which is grouped by
any property of a returned class or component.
Syntax:-
?
update clause :
The UPDATE clause can be used to update one or more properties of one or more objects.
Syntax:-
?
DELETE clause :
Syntax:-
?
Insert clause :
Insert into clause of hibernate query language support where records can be inserted from one object
to another object.
Syntax:-
?
Aggregate Functions
Subqueries
Subqueries are nothing but its a query within another query. Hibernate supports Subqueries if the
underlying database supports it.
Step 1 :
from Employee
Step 2 :
query.setParameter(index,value);
Step 4 : Execute the Query.
we need to call list() method for executing select query on database, it will return java.util.List.For
update and delete queries we need to call executeUpdate() method.For Example:
?
Query :
The Query interface provides many methods.Below are the list of commonly used methods
public int executeUpdate() : is used to execute the update and delete queries.
public List list() : returns the result of the select query as list.
public Query setFirstResult(int rowno): specifies the row no from where record will be retrieved.
public Query setMaxResult(int rowno): specifies the no of records to be retrieved from the table.
public Query setParameter(int position , Object value): It sets the value to the JDBC style query
parameter.
public Query setParameter(String name , Object value): It sets the value to a named query
parameter.
The most important feature in HQL is the alias. Hibernate allows you to assign aliases to the classes in
your query with the as clause. Consider the example given below.
from Employee as e
or
?
The "as" keyword is optional—you can also specify the alias directly after the class name, as
mentioned below:
?
from Employee e
The above query returns all the Employee objects in the database along with all associated object and
non-lazy collections.
If we want to select a Complete Object from the database, we need to use POJO class reference in
place of * while writing the query.Example:
In SQL
?
In HQL
?
from Employee e
If we want to load the Partial Object from the database then we need to replace column names with
POJO class variable names.Example:
In SQL
?
In HQL
?
It is also possible to load or select the object from the database by passing run time values into the
query, in this case we can use either ” ? ” symbol or : label in an HQL command, the index number of
” ? ” will starts from zero and not one. select e from Employee e where e.name=?
?
[ or ]
select e from Employee e where e.name=:mukesh
[ or ]
from Employee e where e.name=?
[ or ]
from Employee e where e.name=:mukesh
Parameter binding is the process of binding a Java variable with an HQL statement.Hibernate
parameter binding is like prepared statements in any normal SQL language.
A simple select query Without parameter binding
?
String name="Mukesh";
Query query = session.createQuery("from Employee where employeeName = '"+name+"' ");
There is two types of query parameter binding in the Hibernate,positional parameter and named
parameter.Hibernate recommend to use the named parameters since it is more flexible and powerful
compare to the positional parameter.
1. Named parameters
In named parameters query string will use parameters in the variable name that can be replaced at
runtime.The actual value will be substituted at runtime using the setParameter() method.
You define a named place holder by writing the place holder name after a colon (:) as :holder name
and use it within a setXXX method without the colon (:) as "holder name".
setParameter
The setParameter is smart enough to discover the parameter data type for you.
?
setString
You can use setString to tell Hibernate this parameter date type is String.
?
The above code tells Hibernate to insert an object of type String in the query. You can also use
setInteger,setBoolean etc for the corresponding types.
setProperties
By using setProperties you can pass an object into the parameter binding. Hibernate will automatic
check the object’s properties and match with the colon parameter.
?
2. Positional parameters
This approach will use question mark (?) to define a named parameter, and you have to set your
parameter according to the position sequence. Example:
?
The basic disadvantage of this method is that if you change the orders of the parameters on the query
you have to change the parameter binding code. For Example:
?
The select clause is used to obtain few properties of objects instead of the complete object.
The "from ClassName" syntax returns a List of the class type with all fields in it. You can instead
select one or more fields selectively than the table itself. If you are selecting a single column in the
result, it will return a List of that field type.
Syntax: –
?
System.out.println(n);
If you select more than one field in an HQL statement, query.list will return a list of lists, one list each
for each field.
Syntax: –
?
Integer id = (Integer)user[0];
System.out.println(id);
In this tutorial we will discuss how to implement a one-to-one association using XML
mapping approach by creating a sample Hibernate application using mysql and eclipse.
In one-to-one relationship, one object of the one pojo class associated with exactly one object
of the another pojo class.
Let us consider relationship between student and student_address. one student has only one
address so this is an example of one to one relationship.consider the relationship as shown
below.
Hibernate Tutorial
Hibernate Basics
Hibernate Inheritance Mapping
Hibernate Query Language (HQL)
Composite Primary Keys In Hibernate
In this relationship a student has only one address. It is called unidirectional one-to-one
association on a foreign key. In this relationship parent table (STUDENT) refers to child
table (STUDENT_ADDRESS) by a foreign key (student_id) and the navigation is one-way
from the student to the address. it’s possible to know address of a student, but not vice-versa.
Student.java
?
1 package com.javawebtutor.hibernate.pojo;
2
3 public class Student {
private long id;
4 private String firstName;
5 private String lastName;
6 private String email;
7 private String phone;
private StudentAddress studentAddress;
8
9 public Student(String firstName, String lastName, String email,
10String phone) {
11 super();
12 this.firstName = firstName;
13 this.lastName = lastName;
this.email = email;
14 this.phone = phone;
15 }
16
17 public long getId() {
18 return id;
19 }
20 public void setId(long id) {
21 this.id = id;
22 }
23
24 public String getFirstName() {
25 return firstName;
}
26
27 public void setFirstName(String firstName) {
28 this.firstName = firstName;
29 }
30
31 public String getLastName() {
32 return lastName;
}
33
34 public void setLastName(String lastName) {
35 this.lastName = lastName;
36 }
37
38 public String getEmail() {
39 return
}
email;
40
41 public void setEmail(String email) {
42
43
44
45
46 this.email = email;
47 }
48
49 public String getPhone() {
50 return
}
phone;
51
52 public void setPhone(String phone) {
53 this.phone = phone;
54 }
55
56 public StudentAddress getStudentAddress() {
return studentAddress;
57 }
58
59 public void setStudentAddress(StudentAddress studentAddress) {
60 this.studentAddress = studentAddress;
61 }
62
63}
64
65
66
67
StudentAddress.java
?
1 package com.javawebtutor.hibernate.pojo;
2
3 public class StudentAddress {
private long id;
4 private String address;
5 private String city;
6 private String state;
7 private String country;
private Student student;
8
9 public StudentAddress() {
10
11 }
12
13 public StudentAddress(String address, String city, String state,
14 String country) {
15 super();
this.address = address;
16 this.city = city;
17 this.state = state;
18 this.country = country;
19 }
20
21 public long getId() {
22 return id;
}
23
24 public void setId(long id) {
25 this.id = id;
26 }
27
28 public String getAddress() {
return address;
29 }
30
31 public void setAddress(String address) {
32 this.address = address;
33 }
34
35 public String getCity() {
return city;
36 }
37
38 public void setCity(String city) {
39 this.city = city;
40 }
41
42 public String getState() {
return state;
43 }
44
45 public void setState(String state) {
46 this.state = state;
47 }
48
public String getCountry() {
49 return country;
50 }
51
52 public void setCountry(String country) {
53 this.country = country;
54 }
55
public Student getStudent() {
56 return student;
57 }
58
59 public void setStudent(Student student) {
60 this.student = student;
61 }
62 }
63
64
65
66
67
68
69
70
71
72
Note:- In above model classes, id is common. This is the primary key of STUDENT table
that exhibits One-to-one relationship with STUDENT_ADDRESS table.
HibernateUtil.java
?
1
2 package com.javawebtutor.hibernate.util;
3
4 import org.hibernate.SessionFactory;
5 import org.hibernate.cfg.Configuration;
6
public class HibernateUtil {
7
8 private static final SessionFactory sessionFactory =
9 buildSessionFactory();
10
11 private static SessionFactory buildSessionFactory() {
12 try {
// Create the SessionFactory from hibernate.cfg.xml
13 return new Configuration().configure().buildSessionFactory();
14 } catch (Throwable ex) {
15 System.err.println("SessionFactory creation failed." + ex);
16 throw new ExceptionInInitializerError(ex);
17 }
}
18
19 public static SessionFactory getSessionFactory() {
20 return sessionFactory;
21 }
22}
23
student.hbm.xml
?
1 <?xml version="1.0" encoding="UTF-8"?>
2
3 <!DOCTYPE hibernate-mapping PUBLIC
4 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
5
6 <hibernate-mapping package="com.javawebtutor.hibernate.pojo">
7
8 <class name="Student" table="STUDENT">
9
10 <id name="id" type="java.lang.Long" column="student_id">
11 <generator class="native" />
</id>
12 <one-to-one name="studentAddress"
13 class="com.javawebtutor.hibernate.pojo.StudentAddress"
14cascade="save-update"></one-to-one>
15
16 <property name="firstName" column="first_name" />
17 <property name="lastName" column="last_name" />
<property name="email" column="email" />
18 <property name="phone" column="phone" />
19
20
21 </class>
22</hibernate-mapping>
23
studentaddress.hbm.xml
?
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
4
5 <hibernate-mapping package="com.javawebtutor.hibernate.pojo">
6
7 <class name="StudentAddress" table="STUDENT_ADDRESS">
8 <id name="id" type="long">
<column name="student_id" />
9 <generator class="foreign">
10 <param name="property">student</param>
11 </generator>
12 </id>
13 <one-to-one name="student"
class="com.javawebtutor.hibernate.pojo.Student"
14 constrained="true"></one-to-one>
15
16 <property name="address" type="string">
17 <column name="address"></column>
18 </property>
19 <property name="city" type="string">
<column name="city"></column>
20 </property>
21 <property name="state" type="string">
22 <column name="state"></column>
23 </property>
24
25
26 <property name="country" type="string">
<column name="country"></column>
27 </property>
28
29 </class>
30</hibernate-mapping>
31
32
hibernate.cfg.xml
?
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
3 "http://hibernate.sourceforge.net/hibernate-configuration-
4 3.0.dtd">
5 <hibernate-configuration>
6 <session-factory>
<!-- specify database driver -->
7 <property
8 name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
9 <property name="hibernate.connection.url">
1 jdbc:mysql://localhost/hibernatedb</property>
0 <!-- database username -->
<property name="hibernate.connection.username">root</property>
1 <!-- database password -->
1 <property name="connection.password">mukesh</property>
1 <!-- database dialect, different for different databases -->
2 <property name="hibernate.dialect">
1 org.hibernate.dialect.MySQLDialect</property>
<!-- true value shows SQL query that is generated by hibrnate -->
3 <property name="show_sql">true</property>
1 <!-- path of hibernate mapping file -->
4 <mapping
1 resource="com/javawebtutor/hibernate/pojo/student.hbm.xml"></mapping>
<mapping
5 resource="com/javawebtutor/hibernate/pojo/studentaddress.hbm.xml"></
1 mapping>
6 </session-factory>
1 </hibernate-configuration>
7
1
8
1
9
2
0
2
1
2
2
In the above hibernate mapping file we are implementing One-to-one relationship. For both
the model classes we are using a single primary key id. In studentaddress.hbm file we have
defined a foreign identifier generator so that primary it uses primary key of Studenttable.
Test.java
?
1 package com.javawebtutor.hibernate.client;
2
3 import java.util.Date;
4
import org.hibernate.Session;
5 import org.hibernate.SessionFactory;
6
7 import com.javawebtutor.hibernate.model.Bank;
8 import com.javawebtutor.hibernate.model.Customer;
9 import com.javawebtutor.hibernate.util.HibernateUtil;
10
public class Test {
11 public static void main(String[] args) {
12
13 SessionFactory sf = HibernateUtil.getSessionFactory();
14 Session session = sf.openSession();
15 session.beginTransaction();
16
17 Bank bank = new Bank();
bank.setBankName("HDFC");
18 session.save(bank);
19 Date birthDate = new java.util.Date();
20 birthDate = new java.util.Date(83, 02, 22);
21 Customer customer = new Customer("Mukesh", "Kumar", birthDate,
22 "8939651567");
Customer customer1 = new Customer("Ravi", "Raj", birthDate,
23"12345678");
24 customer.setBank(bank);
25 customer1.setBank(bank);
26
27 session.save(customer);
28 session.save(customer1);
29 session.getTransaction().commit();
30 session.close();
31 }
32}
33
34
35
36
Output :
Now Run Test.java, you will get following output in the eclipse console.
SQL Output :
In this tutorial we are going to understand how to map a one-to-many association between
Java objects and database tables using Hibernate framework. We will create a sample
Hibernate-based application to manage the following entity relationship:
In this relationship,one row in a table can be mapped to multiple rows in another table. For
example, think of a Bank where we have another table for Customer. A Bank can have
multiple Customers, so here we can implement one-to-many Mapping.
Create Tables :
For this example, we used MYSQL Database. Create following two tables in MySQL.Each
Bank can be associated with multiple Customer.
Hibernate Tutorial
Hibernate Basics
Hibernate Inheritance Mapping
Hibernate Query Language (HQL)
Composite Primary Keys In Hibernate
Project Structure :
Create a simple java project in Eclipse, and add hibernate related jar files to the classpath of
the project. The final project structure is given below.
Bank.java
?
1 package com.javawebtutor.hibernate.model;
2
import java.util.Set;
3
4
public class Bank {
5
6 private Long bankId;
7
8 private String bankName;
9
1 private Set<Customer> customers;
0
public Long getBankId() {
1
return bankId;
1 }
1
2 public void setBankId(Long bankId) {
1 this.bankId = bankId;
3 }
1
public String getBankName() {
4 return bankName;
1 }
5
1 public void setBankName(String bankName) {
6 this.bankName = bankName;
1 }
7
public Set<Customer> getCustomers() {
1 return customers;
8 }
1
9 public void setCustomers(Set<Customer> customers) {
2 this.customers = customers;
}
0
2
}
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
I am using Set of Customers, so that every record is unique. We can also use List or Array for
one-to-one mapping.
Customer.java
?
1 package com.javawebtutor.hibernate.model;
2
3 import java.util.Date;
4 public class Customer {
5
6 private Long customerId;
7 private String firstname;
8 private String lastname;
9 private Date birthDate;
private String cellphone;
10 private Bank bank;
11
12 public Customer(String firstname, String lastname, Date birthDate,
13 String cellphone) {
14 this.firstname = firstname;
15 this.lastname = lastname;
this.birthDate = birthDate;
16 this.cellphone = cellphone;
17 }
18
19 public Long getCustomerId() {
20 return customerId;
21 }
22 public void setCustomerId(Long customerId) {
23 this.customerId = customerId;
24 }
25
26 public String getFirstname() {
27 return firstname;
}
28
29 public void setFirstname(String firstname) {
30 this.firstname = firstname;
31 }
32
33 public String getLastname() {
34 return lastname;
}
35
36 public void setLastname(String lastname) {
37
38
39
40
41
42 this.lastname = lastname;
}
43
44 public Date getBirthDate() {
45 return birthDate;
46 }
47
48 public void setBirthDate(Date birthDate) {
49 this.birthDate
}
= birthDate;
50
51 public String getCellphone() {
52 return cellphone;
53 }
54
55 public void setCellphone(String cellphone) {
this.cellphone = cellphone;
56 }
57
58 public Bank getBank() {
59 return bank;
60 }
61
62 public void setBank(Bank bank) {
this.bank = bank;
63 }
64
65}
66
67
68
69
70
HibernateUtil.java
?
1 package com.javawebtutor.hibernate.util;
2
import org.hibernate.SessionFactory;
3 import org.hibernate.cfg.Configuration;
4
5 public class HibernateUtil {
6
7
8 private static final SessionFactory sessionFactory =
9 buildSessionFactory();
10
11 private static SessionFactory buildSessionFactory() {
12 try {
// Create the SessionFactory from hibernate.cfg.xml
13 return new Configuration().configure().buildSessionFactory();
14 } catch (Throwable ex) {
15 System.err.println("SessionFactory creation failed." + ex);
16 throw new ExceptionInInitializerError(ex);
}
17 }
18
19 public static SessionFactory getSessionFactory() {
20 return sessionFactory;
21 }
22}
23
bank.hbm.xml
?
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
4
5 <hibernate-mapping package="com.javawebtutor.hibernate.model">
6
7 <class name="Bank" table="BANK">
8
9 <id name="bankId" type="java.lang.Long" column="department_id">
<generator class="native" />
10 </id>
11
12 <property name="bankName" column="bank_name" />
13
14 <set name="customers" table="CUSTOMER" inverse="true" lazy="true"
15 fetch="select">
16 <key>
<column name="bank_id" not-null="true" />
17 </key>
18 <one-to-many
19class="com.javawebtutor.hibernate.model.Customer" />
20 </set>
21
22 </class>
23</hibernate-mapping>
24
25
customer.hbm.xml
?
1
2 <?xml version="1.0" encoding="UTF-8"?>
3 <!DOCTYPE hibernate-mapping PUBLIC
4 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
5
6 <hibernate-mapping package="com.javawebtutor.hibernate.model">
7
8 <class name="Customer" table="CUSTOMER">
9 <id name="customerId" column="customer_id">
10 <generator class="native" />
11 </id>
12
<property name="firstname" />
13 <property name="lastname" column="lastname" />
14 <property name="birthDate" type="date" column="birth_date" />
15 <property name="cellphone" column="cell_phone" />
16
17
18 <many-to-one name="bank"
19class="com.javawebtutor.hibernate.model.Bank"
fetch="select">
20 <column name="bank_id" not-null="true" />
21 </many-to-one>
22
23 </class>
24</hibernate-mapping>
25
hibernate.cfg.xml
?
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
3 "http://hibernate.sourceforge.net/hibernate-configuration-
4 3.0.dtd">
5 <hibernate-configuration>
6 <session-factory>
<!-- specify database driver -->
7 <property
8 name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
9 <property name="hibernate.connection.url">
10jdbc:mysql://localhost/hibernate</property>
11 <!-- database username -->
<property name="hibernate.connection.username">root</property>
12
<!-- database password -->
13 <property name="connection.password">mukesh</property>
14 <!-- database dialect, different for different databases -->
15 <property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect</property>
16 <!-- true value shows SQL query that is generated by hibrnate -->
17 <property name="show_sql">true</property>
18 <!-- to bind hibernate session to current running java thread -->
19 <property name="current_session_context_class">thread</property>
20 <!-- path of hibernate mapping file -->
<mapping
21resource="com/javawebtutor/hibernate/model/bank.hbm.xml"></mapping>
22 <mapping
23resource="com/javawebtutor/hibernate/model/customer.hbm.xml"></mapping>
24 </session-factory>
</hibernate-configuration>
Note:- Update the database username and password corresponding to your database settings.
Test.java
?
1 package com.javawebtutor.hibernate.client;
2
3 import java.util.Date;
4
import org.hibernate.Session;
5 import org.hibernate.SessionFactory;
6
7 import com.javawebtutor.hibernate.model.Bank;
8 import com.javawebtutor.hibernate.model.Customer;
9 import com.javawebtutor.hibernate.util.HibernateUtil;
10
public class Test {
11 public static void main(String[] args) {
12
13 SessionFactory sf = HibernateUtil.getSessionFactory();
14 Session session = sf.openSession();
15 session.beginTransaction();
16
17 Bank bank = new Bank();
bank.setBankName("HDFC");
18 session.save(bank);
19 Date birthDate = new java.util.Date();
20 birthDate = new java.util.Date(83, 02, 22);
21 Customer customer = new Customer("Mukesh", "Kumar", birthDate,
22 "8939651567");
Customer customer1 = new Customer("Ravi", "Raj", birthDate,
23"12345678");
24 customer.setBank(bank);
25 customer1.setBank(bank);
26
27
28
29 session.save(customer);
30 session.save(customer1);
31
session.getTransaction().commit();
32 session.close();
33 }
34}
35
36
Output :
Now Run Test.java, you will get following output in the eclipse console.
SQL Output :
Hibernate Tutorial
Hibernate Basics
Hibernate Inheritance Mapping
Hibernate Query Language (HQL)
Composite Primary Keys In Hibernate
In table per class hierarchy, only one table is created with columns to accommodate all the
properties of each class involved in hierarchy. Because all the records of each class are
available in a single table, to differentiate which record belongs to which class, we create one
extra column known as discriminator column. Each class identified by some name (alias
name) and this name is stored in the discriminator column.
In table per class hierarchy,One table will be created for above hierarchy.i.e. EMPLOYEE
table will be created having following structure.
EMPLOYEE
--------------
EMP_ID
EMP_NAME
DESIGNATION
DEPARTMENT
WORKING_DAYS
CONTRACTOR_NAME
Employee.java
?
1
2
3
4
5
6
7
8
9 package com.jwt.hibernate;
1
0 public class Employee {
1 private int empId;
1 private String empName;
1
2 public int getEmpId() {
return empId;
1 }
3
1 public void setEmpId(int empId) {
4 this.empId = empId;
1 }
5
public String getEmpName() {
1 return empName;
6 }
1
7 public void setEmpName(String empName) {
1 this.empName = empName;
8 }
1
}
9
2
0
2
1
2
2
2
3
PermanentEmployee.java:
?
1
2
3
4
5
6
7
8
9 package com.jwt.hibernate;
1
0 public class PermanentEmployee extends Employee {
1 private String designation;
1 private String department;
1
2 public String getDesignation() {
return designation;
1 }
3
1 public void setDesignation(String designation) {
4 this.designation = designation;
1 }
5
public String getDepartment() {
1 return department;
6 }
1
7 public void setDepartment(String department) {
1 this.department = department;
8 }
1
}
9
2
0
2
1
2
2
2
3
ContractEmployee.java:
?
1 package com.jwt.hibernate;
2
3 public class ContractEmployee extends Employee {
private int workingDays;
4 private String contractorName;
5
6 public int getWorkingDays() {
7 return workingDays;
8
9 }
10
11 public void setWorkingDays(int workingDays) {
12 this.workingDays = workingDays;
13 }
14
public String getContractorName() {
15 return contractorName;
16 }
17
18 public void setContractorName(String contractorName) {
19 this.contractorName = contractorName;
20 }
21
}
22
23
hibernate-cfg.xml
?
1
2
3
4
5 <?xml version="1.0" encoding="utf-8"?>
6 <!DOCTYPE hibernate-configuration PUBLIC
7 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
8 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
9
<hibernate-configuration>
1 <session-factory>
0 <property
1 name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
1 <property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/jwt</property
1 >
2 <property name="hibernate.connection.username">root</property>
1 <property name="hibernate.connection.password">mukesh</property>
3 <property
1 name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
4 <property name="format_sql">true</property>
1 <property name="hbm2ddl.auto">create </property>
5 <mapping resource="com/jwt/hibernate/employee.hbm.xml" />
1 </session-factory>
6 </hibernate-configuration>
1
7
1
8
employee.hbm.xml
?
1 <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC
2 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
3 <hibernate-mapping>
<class name="com.jwt.hibernate.Employee" table="EMPLOYEE">
4 <id name="empId" column="EMP_ID" />
5 <discriminator column="DIS_COL" type="string" length="10" />
6 <property name="empName" column="EMP_NAME" length="50" />
7 <subclass name="com.jwt.hibernate.PermanentEmployee"
discriminator-value="PE">
8 <property name="designation" column="DESIGNATION" length="50"
9 />
10 <property name="department" column="DEPARTMENT" length="50" />
11 </subclass>
12 <subclass name="com.jwt.hibernate.ContractEmployee" discriminator-
value="CE">
13 <property name="workingDays" column="WORKING_DAYS" />
14 <property name="contractorName" column="CONTRACTOR_NAME"
15 length="50" />
16 </subclass>
</class>
17</hibernate-mapping>
Note that we have defined only one hibernate mapping (hbm) file employee.hbm.xml. All
classes are defined within one hbm file.
Now create a Test class for the purpose of inserting the data into the DB
Test.java:
?
1 package com.jwt.hibernate;
2
3 import org.hibernate.Session;
import org.hibernate.SessionFactory;
4 import org.hibernate.Transaction;
5 import org.hibernate.cfg.Configuration;
6
7 public class Test {
8 public static void main(String[] args) {
Configuration cfg = new Configuration();
9 cfg.configure("hibernate.cfg.xml");
10 SessionFactory sf = cfg.buildSessionFactory();
11 Session session = sf.openSession();
12 // create two objects of PermanentEmployee
13 PermanentEmployee p1 = new PermanentEmployee();
p1.setEmpId(34326);
14 p1.setEmpName("Mukesh Kumar");
15 p1.setDesignation("SE");
16 p1.setDepartment("RLT");
17 PermanentEmployee p2 = new PermanentEmployee();
p2.setEmpId(1894);
18
19
20
21
22 p2.setEmpName("Neil Raj");
23 p2.setDesignation("Doctor");
24 p2.setDepartment("Surgery");
25 // create two objects of
ContractEmployee c1 = new ContractEmployee();
26 c1.setEmpId(1234);
27 c1.setEmpName("Vidya Rnjan");
28 c1.setWorkingDays(28);
29 c1.setContractorName("Naveen");
ContractEmployee c2 = new ContractEmployee();
30 c2.setEmpId(1567);
31 c2.setEmpName("Suman");
32 c2.setWorkingDays(22);
33 c2.setContractorName("Divya");
34 // now save all four objects
Transaction tx = session.beginTransaction();
35 session.save(p1);
36 session.save(c1);
37 session.save(p2);
38 session.save(c2);
tx.commit();
39 session.close();
40 sf.close();
41 System.out.println("Objects saved");
42 }
43
44}
45
46
47
48
A CRUD operation deals with creating , retrieving , updating and deleting records from the
table, in this tutorial we will see how it is done.We are going to discuss about 4 main
functionality:
1. Create a record
2. Read a record
3. Update a Record
4. Delete a Record
First, lets create the database and table for Employee using the following SQL
scripts.Following script will create database and table in mysql:
create database jwt;
Hibernate Tutorial
Hibernate Basics
Hibernate Inheritance Mapping
Hibernate Query Language (HQL)
Composite Primary Keys In Hibernate
Employee.java
1 package com.jwt.hibernate;
2
3 import java.io.Serializable;
4
public class Employee implements Serializable {
5
6
private static final long serialVersionUID = 1L;
7
private int id;
8
private String name;
9
private int sal;
10 private String city;
11 private int phone;
12
21 return name;
22 }
23
25 this.name = name;
}
26
27
public int getSal() {
28
return sal;
29
}
30
31
public void setSal(int sal) {
32
this.sal = sal;
33 }
34
36 return city;
37 }
38
43
44
public int getPhone() {
45
return phone;
46
}
47
48
public void setPhone(int phone) {
49
this.phone = phone;
50
}
51
52}
53
54
hibernate.cfg.xml
1 <property name="hibernate.connection.password">mukesh</property>
1 <property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
1
2
1
3
<property name="show_sql">true</property>
1
4 <property name="format_sql">true</property>
1 </hibernate-configuration>
6
1
7
Employee.hbm.xml
1
<?xml version="1.0"?>
2
<!DOCTYPE hibernate-mapping PUBLIC
3
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
4
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
5
<hibernate-mapping>
6 <class name="com.jwt.hibernate.Employee" table="EMPCRUD">
9 </id>
16
Step 5 : Create utility class HibernateUtil to get
SessionFactory Object
HibernateUtil.java
1
package com.jwt.hibernate.util;
2
3
import org.hibernate.SessionFactory;
4
import org.hibernate.cfg.Configuration;
5
6
public class HibernateUtil {
7
private static final SessionFactory sessionFactory;
8
static {
9 try {
11 .buildSessionFactory();
20}
21
Main.java
?
1 package com.jwt.hibernate.main;
2
3 import java.util.Iterator;
import java.util.List;
4
import org.hibernate.HibernateException;
5
import org.hibernate.Query;
6
import org.hibernate.Session;
7
import org.hibernate.Transaction;
8
9 import com.jwt.hibernate.Employee;
10 import com.jwt.hibernate.util.HibernateUtil;
11
21
22 public void saveEmployee(String name, String city, int sal, int phone)
{
23
Session session =
24 HibernateUtil.getSessionFactory().openSession();
26
27 try {
28 transaction = session.beginTransaction();
Employee employee = new Employee();
29
employee.setName("name");
30
employee.setSal(sal);
31
32 employee.setCity("city");
33 employee.setPhone(phone);
session.save(employee);
34
transaction.commit();
35
System.out.println("Records inserted sucessessfully");
36
} catch (HibernateException e) {
37
transaction.rollback();
38 e.printStackTrace();
39 } finally {
40 session.close();
41 }
42
43 }
44
public void retriveEmployee()
45
46
{
47
48
Session session =
49 HibernateUtil.getSessionFactory().openSession();
51 try {
52 transaction = session.beginTransaction();
List employee = session.createQuery("from Employee").list();
53
54
for (Iterator iterator = employee.iterator();
55 iterator.hasNext();) {
64
65 transaction.rollback();
66
e.printStackTrace();
67
68
} finally {
69
70
session.close();
71
72
}
73
}
74
75 public void deleteEmployee() {
76
77 Session session =
HibernateUtil.getSessionFactory().openSession();
78
Transaction transaction = null;
79
try {
80
transaction = session.beginTransaction();
81
String queryString = "from Employee where phone = :phone";
82 Query query = session.createQuery(queryString);
83 query.setInteger("phone", 893965);
85 session.delete(employee);
87
} catch (HibernateException e) {
88
89
transaction.rollback();
90
91
e.printStackTrace();
92
93
94 } finally {
95
96 session.close();
97
}
98
}
99
10
0 public void updateEmployee() {
10
1 Session session =
HibernateUtil.getSessionFactory().openSession();
10
2 Transaction transaction = null;
10 try {
3 transaction = session.beginTransaction();
10 query.setInteger("sal", 50000);
5
Employee employee = (Employee) query.uniqueResult();
10
employee.setSal(60000);
6
session.update(employee);
10
7 System.out.println("Employee records updated!");
} catch (HibernateException e) {
10
8
10 transaction.rollback();
9
11 e.printStackTrace();
0
11
1 } finally {
11
2 session.close();
11
3
}
11
}
4
11
5
11
6
11
7
11
8
11
9
12
0
12
1
12
}
2
12
3
12
4
12
5
12
6
12
7
12
8
12
9
Output :
If data is inserted into DB you can see inserted/updated/deleted data in mysql console as
shown below.
Integrating JSP,Servlet and Hibernate in an MVC application
May 1, 2015 by Mukesh Kumar at 3:47 pm
Project Description :
In this article, we are going to create a real time MVC application by using Servlet, JSP and
Hibernate.This example is developed using MVC pattern, where JSP pages acts as view
layer, Hibernate and MySQL database as the model and servlet as controller layer. Its a very
simple and basic application and entire codes is self explanatory.
In this tutorial, we are going to create a web application by using servlet,jsp and hibernate.
When user will access the application ,login page will be displayed. For first time user there
is a link for the registration. Once user will register his/her details will be collected in servlet
and finally data will be saved into database by using hibernate.
Once user got registered , user can login to the application and use the website. If user enters
wrong credential error page will be displayed.
Hibernate Tutorial
Hibernate Basics
Hibernate Inheritance Mapping
Hibernate Query Language (HQL)
Composite Primary Keys In Hibernate
For creating the application in Eclipse, follow the steps mentioned below.
login.jsp
?
7 </head>
8 <body>
23</div>
24<br />
<span class="login-box-options">
25
New User? <a href="register.jsp" style="margin-left:30px;">Register
26Here</a>
27
28</span>
<br />
29
<br />
30
<input style="margin-left:100px;" type="submit" value="Login" />
31
</div>
32
</div>
33</form>
34</body>
35</html>
36
register.jsp
?
1 <html>
2 <head>
<title>Registration Form</title>
3
<style type="text/css">
4
h3{font-family: Calibri; font-size: 22pt; font-style: normal; font-
5 weight: bold; color:SlateBlue;
16<tr>
17<td>First Name</td>
20</tr>
<tr>
21
<td>Middle Name</td>
22
<td><input type="text" name="middleName" maxlength="30"/>
23
(max 30 characters a-z and A-Z)
24
</td>
25</tr>
26<tr>
27<td>Last Name</td>
35<tr>
36<td>User ID</td>
38</tr>
<tr>
39
<td>Password</td>
40
<td><input type="text" name="password" maxlength="100" /></td>
41
</tr>
42
<tr>
43<td colspan="2" align="center">
46</td>
47</tr>
48</table>
</form>
49
50
51
52</body>
53</html>
54
55
home.jsp
?
1 <%@page import="java.util.List"%>
2 <%@page import="com.javawebtutor.service.LoginService"%>
<%@page import="java.util.Date"%>
3
<%@page import="com.javawebtutor.model.User"%>
4
<%@page contentType="text/html" pageEncoding="UTF-8"%>
5
<!DOCTYPE html>
6
<html>
7 <head>
10 <title>Result Page</title>
11</head>
<body>
12
<center>
13
<div id="container">
14
<h1>Result Page</h1>
15
<b>This is Sample Result Page</b><br/>
16 <%=new Date()%></br>
17 <%
19 %>
24
25 <table>
<thead>
26
<tr>
27
<th>User ID</th>
28
<th>First Name</th>
29
<th>Middle Name</th>
30 <th>Last Name</th>
31 <th>email</th>
32 </tr>
33 </thead>
34 <tbody>
<%
35
LoginService loginService = new LoginService();
36
List<User> list = loginService.getListOfUsers();
37
for (User u : list) {
38
%>
39 <tr>
40 <td><%=u.getUserId()%></td>
41 <td><%=u.getFirstName()%></td>
42 <td><%=u.getMiddleName()%></td>
43 <td><%=u.getLastName()%></td>
<td><%=u.getEmail()%></td>
44
</tr>
45
<%}%>
46
<tbody>
47
</table>
48 <br/>
49 </div>
50 </center>
51</body>
52</html>
53
54
55
56
57
logout.jsp
?
2 <html>
<head>
3
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
4
<link rel="stylesheet" type="text/css" href="css/style.css">
5
<title>logout Page</title>
6
</head>
7 <body>
8 <%
9 session.removeAttribute("userId");
10 session.removeAttribute("password");
11 session.invalidate();
%>
12
<center>
13
<h1>You have successfully logged out</h1>
14
To login again <a href="login.jsp">click here</a>.
15
</center>
16</body>
17</html>
18
error.jsp
?
8 </head>
9 <body>
10<center>
style.css
?
1 body{
6 .spacer{clear:both; height:1px;}
7 .mainform{
margin:0 auto;
8
width:400px;
9
padding:14px;
10
}
11
12
#container{
13 border:solid 2px burlywood;
14 background: silver;
border-radius: 5px;
15
}
16
#container h1 {
17
font-size:14px;
18
font-weight:bold;
19 margin-bottom:8px;
20 }
21 #container p{
22 font-size:11px;
23 color:#666666;
margin-bottom:20px;
24
border-bottom:solid 1px burlywood;
25
padding-bottom:10px;
26
}
27
#container label{
28 display:block;
29 font-weight:bold;
30 text-align:right;
31 width:140px;
32 float:left;
}
33
#container .small{
34
color:#666666;
35
display:block;
36
font-size:11px;
37 font-weight:normal;
38 text-align:right;
39 width:140px;
40 }
41 #container input{
float:left;
42
font-size:12px;
43
44 padding:4px 2px;
51 margin-left:150px;
52 width:125px;
53 height:31px;
54 background:#666666;
text-align:center;
55
line-height:31px;
56
color:#FFFFFF;
57
font-size:11px;
58
font-weight:bold;
59 border-radius: 5px;
60 }
62 border-radius: 5px;
63 border:solid 1px;
padding: 5px;
64
width: max-content;
65
}
66
67
68
#login-box {
69
width:333px;
70 height: 352px;
72 color: #ebebeb;
74 margin-top: -70px;
75 background: url(../images/login-box-backg.png) no-repeat left top;
76 }
77
#login-box img {
78
border:none;
79
}
80
81
#login-box h2 {
82
padding:0;
83 margin:0;
84 color: #ebebeb;
86 }
87
88
89 #login-box-name {
float: left;
90
display:inline;
91
width:80px;
92
text-align: right;
93
padding: 14px 10px 0 0;
94 margin:0 0 7px 0;
95 }
96
97 #login-box-field {
98 float: left;
99 display:inline;
width:230px;
10
0 margin:0;
10 margin:0 0 7px 0;
1 }
10
2
10
3 .form-login {
10 width: 205px;
4 padding: 10px 4px 6px 3px;
10 font-size: 16px;
6
color: #ebebeb;
10
}
7
10
8
10 .login-box-options {
9 clear:both;
11 padding-left:87px;
0
font-size: 11px;
11 }
1
11
2 .login-box-options a {
color: #ebebeb;
11
3 font-size: 11px;
11 }
4
11
5
11
6
11
7
11
8
11
9
12
0
12
1
12
2
12
3
12
4
12
5
12
6
12
7
12
8
12
9
13
0
13
1
13
2
13
3
13
4
User.java
?
1 package com.javawebtutor.model;
2
3 import java.io.Serializable;
import javax.persistence.Entity;
4 import javax.persistence.GeneratedValue;
5 import javax.persistence.Id;
import javax.persistence.Table;
6
7
@Entity
8
@Table(name="USER_TABLE")
9
public class User implements Serializable {
10
11
@Id @GeneratedValue
12 private Long id;
25 this.firstName = firstName;
this.middleName = middleName;
26
this.lastName = lastName;
27
this.email = email;
28
this.userId = userId;
29
this.password = password;
30
}
31
32
33 public Long getId() {
34
35 return id;
36 }
37
public void setId(Long id) {
38
this.id = id;
39
}
40
41
public String getFirstName() {
42
return firstName;
43 }
44
46 this.firstName = firstName;
47 }
48
58 }
59
61 this.lastName = lastName;
62 }
63
public String getEmail() {
64
return email;
65
66
67
68
}
69
70
public void setEmail(String email) {
71
this.email = email;
72
}
73
74
public String getUserId() {
75 return userId;
76 }
77
79 this.userId = userId;
80 }
81
public String getPassword() {
82
return password;
83
}
84
85
public void setPassword(String password) {
86
this.password = password;
87
}
88}
89
90
91
1 package com.jwt.hibernate.bean;
2
9
10 public int getId() {
11 return id;
12 }
13
15 this.id = id;
}
16
17
public String getUserName() {
18
return userName;
19
}
20
21
public void setUserName(String userName) {
22 this.userName = userName;
23 }
24
26 return password1;
27 }
28
29
30
32 this.password1 = password1;
33 }
34
public String getEmail() {
35
return email;
36
}
37
38
public void setEmail(String email) {
39
this.email = email;
40 }
41
43 return phone;
44 }
45
54 this.city = city;
55 }
56
57}
58
59
Step 6 : Create Util class for getting SeesionFactory
Object
Create a java class HibernateUtil. Method inside this class will return SessionFactory
Object.SessionFactory is heavy weight object.For better performance only one
SessionFactory should be created for entire application. So this class should be created as
singleton.
HibernateUtil.java
?
1 package com.javawebtutor.hibernate.util;
2
3 import org.hibernate.Session;
import org.hibernate.SessionFactory;
4
import org.hibernate.cfg.AnnotationConfiguration;
5
6
public class HibernateUtil {
7
8
private static final SessionFactory sessionFactory;
9
1
static {
0
try {
1
1 sessionFactory = new
AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFact
1 ory();
2 } catch (Throwable ex) {
1 }
5
1
public static Session openSession() {
6
return sessionFactory.openSession();
1
7 }
1 }
8
1
9
2
0
2
1
2
2
2
3
hibernate.cfg.xml
?
4 <hibernate-configuration>
5 <session-factory>
<property
6 name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
7 <property
name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
8
<property
9 name="hibernate.connection.url">jdbc:mysql://localhost:3306/jwt</property
>
1
0 <property name="hibernate.connection.username">root</property>
1 <property name="hibernate.connection.password">mukesh</property>
1 <property name="show_sql">true</property>
1 <property name="hbm2ddl.auto">update</property>
2 <mapping class="com.javawebtutor.model.User" />
1 </session-factory>
3
1
</hibernate-configuration>
4
LoginServlet.java
?
1 package com.javawebtutor.controller;
2
3 import java.io.IOException;
import javax.servlet.ServletException;
4
import javax.servlet.http.HttpServlet;
5
import javax.servlet.http.HttpServletRequest;
6
import javax.servlet.http.HttpServletResponse;
7
8
import com.javawebtutor.model.User;
9 import com.javawebtutor.service.LoginService;
10
11
12public class LoginServlet extends HttpServlet {
21 if(result == true){
22
23 request.getSession().setAttribute("user", user);
response.sendRedirect("home.jsp");
24
}
25
else{
26
response.sendRedirect("error.jsp");
27
}
28}
29
30}
31
RegisterServlet.java
?
1 package com.javawebtutor.controller;
2
3 import java.io.IOException;
import java.io.PrintWriter;
4
import javax.servlet.ServletException;
5
import javax.servlet.http.HttpServlet;
6
import javax.servlet.http.HttpServletRequest;
7
import javax.servlet.http.HttpServletResponse;
8
9 import com.javawebtutor.model.User;
10import com.javawebtutor.service.RegisterService;
11
12
25
26 try {
33 out.println("<center>");
34 if(result){
38 out.println("<h1>Registration Failed</h1>");
45 out.close();
46 }
47}
48
}
49
50
51
LoginService.java
?
1 package com.javawebtutor.service;
2
3 import java.util.ArrayList;
import java.util.List;
4
import org.hibernate.Query;
5
import org.hibernate.Session;
6
import org.hibernate.Transaction;
7
8
import com.javawebtutor.hibernate.util.HibernateUtil;
9 import com.javawebtutor.model.User;
10
11public class LoginService {
12
18 return false;
19 }
20 }
21
24 Transaction tx = null;
User user = null;
25
try {
26
tx = session.getTransaction();
27
tx.begin();
28
Query query = session.createQuery("from User where
29userId='"+userId+"'");
user = (User)query.uniqueResult();
30
tx.commit();
31
} catch (Exception e) {
32
if (tx != null) {
33
tx.rollback();
34
}
35 e.printStackTrace();
36 } finally {
37 session.close();
38 }
39 return user;
}
40
41
public List<User> getListOfUsers(){
42
List<User> list = new ArrayList<User>();
43
Session session = HibernateUtil.openSession();
44
Transaction tx = null;
45 try {
46 tx = session.getTransaction();
47 tx.begin();
48 list = session.createQuery("from
User").list();
49
tx.commit();
50
} catch (Exception e) {
51 if (tx != null) {
52 tx.rollback();
53 }
54
55
e.printStackTrace();
56
} finally {
57
session.close();
58
}
59
return list;
60
}
61}
62
63
RegisterService.java
?
1 package com.javawebtutor.service;
2 import org.hibernate.Query;
import org.hibernate.Session;
3
import org.hibernate.Transaction;
4
5
import com.javawebtutor.hibernate.util.HibernateUtil;
6
import com.javawebtutor.model.User;
7
public class RegisterService {
8
9
public boolean register(User user){
10 Session session = HibernateUtil.openSession();
12
13 Transaction tx = null;
14 try {
15 tx = session.getTransaction();
tx.begin();
16
session.saveOrUpdate(user);
17
tx.commit();
18
19 } catch (Exception e) {
26 return true;
27}
28
36userId='"+user.getUserId()+"'");
User u = (User)query.uniqueResult();
37
tx.commit();
38
if(u!=null) result = true;
39
}catch(Exception ex){
40
if(tx!=null){
41 tx.rollback();
42 }
43 }finally{
44 session.close();
45 }
return result;
46
}
47
}
48
49
50
51
web.xml
5 version="2.5">
<display-name>MVCApplication</display-name>
6
<servlet>
7
<display-name>LoginServlet</display-name>
8
<servlet-name>LoginServlet</servlet-name>
9
<servlet-class>com.javawebtutor.controller.LoginServlet</servlet-
10class>
</servlet>
11
<servlet>
12
<display-name>RegisterServlet</display-name>
13
<servlet-name>RegisterServlet</servlet-name>
14
<servlet-class>com.javawebtutor.controller.RegisterServlet</
15servlet-class>
16 </servlet>
<servlet-mapping>
17
<servlet-name>LoginServlet</servlet-name>
18
<url-pattern>/LoginServlet</url-pattern>
19
</servlet-mapping>
20
<servlet-mapping>
21 <servlet-name>RegisterServlet</servlet-name>
22 <url-pattern>/RegisterServlet</url-pattern>
</servlet-mapping>
23 <welcome-file-list>
24 <welcome-file>login.jsp</welcome-file>
25 </welcome-file-list>
</web-app>
Output in Browser :
Login Page
New User Registration Page
Welcome Page
Error Page
Result Page