KEMBAR78
Hibernate | PDF | Databases | Class (Computer Programming)
0% found this document useful (0 votes)
324 views110 pages

Hibernate

The document discusses JDBC, ORM, and Hibernate. It defines JDBC as providing a Java API that allows programs to access databases. ORM is described as a technique that converts data between object-oriented languages and relational databases. Hibernate is summarized as an open-source ORM framework that maps Java classes to database tables and handles object-relational impedance mismatch.

Uploaded by

srinivasareddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
324 views110 pages

Hibernate

The document discusses JDBC, ORM, and Hibernate. It defines JDBC as providing a Java API that allows programs to access databases. ORM is described as a technique that converts data between object-oriented languages and relational databases. Hibernate is summarized as an open-source ORM framework that maps Java classes to database tables and handles object-relational impedance mismatch.

Uploaded by

srinivasareddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 110

What is JDBC?

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.

Hibernate named query using annotation


Named query is a concept of using queries by name. First a query is defined and a name is assigned to
it. Then it can be used anywhere by this alias name.
Syntax of hibernate named query using annotation:
@NamedQueries({
@NamedQuery(name = " queryName ", query = " queryString
")
})
How to call a named query?
We can call the named query by getNamedQuery() method of Session interface.
Query query = session.getNamedQuery("queryName");
Example:
Student.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
 
/**
* This class represents a persistent class for Student.
* @author w3spoint
*/
 
@NamedQueries(
{
@NamedQuery(
name = "getStudentByRollNo",
query = "from Student where rollNo = :rollNo"
)
}
)
@Entity
@Table(name= "STUDENT")
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
@Id
@GeneratedValue
@Column(name = "Student_Id", unique = true, nullable =
false)
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
 
@Column(name = "First_Name")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
 
@Column(name = "Last_Name")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
 
@Column(name = "Class")
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
 
@Column(name = "RollNo")
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
 
@Column(name = "Age")
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 class="com.w3spoint.business.Student"/>
 
</session-factory>
 
</hibernate-configuration>
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 java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
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("Sunil");
student.setLastName("Kunar");
student.setClassName("MCA final");
student.setRollNo("MCA/07/15");
student.setAge(27);
 
//Get the session object.
Session session =
HibernateUtil.getSessionFactory().openSession();
 
//Start hibernate transaction.
session.beginTransaction();
 
//Persist the student object.
session.save(student);
 
//Commit hibernate transaction.
session.getTransaction().commit();
 
//select a student record using named query
Query query =
session.getNamedQuery("getStudentByRollNo");
query.setString("rollNo", "MCA/07/15");
 
List<Student> stuList = (List<Student>) query.list();
for(Student stu : stuList){
System.out.println("First Name: " + stu.getFirstName());
System.out.println("Last Name: " + stu.getLastName());
System.out.println("Class: " + stu.getClassName());
System.out.println("RollNo: " + stu.getRollNo());
System.out.println("Age: " + stu.getAge());
}
 
//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 (?, ?, ?, ?, ?, ?)
Hibernate: select student0_.Student_Id as Student1_0_,
student0_.First_Name as First2_0_, student0_.Last_Name as
Last3_0_, student0_.Class as Class0_, student0_.RollNo as
RollNo0_, student0_.Age as Age0_ from Student
student0_ where student0_.RollNo=?
First Name: Sunil
Last Name: Kunar
Class: MCA final
RollNo: MCA/07/15
Age: 27

Hibernate association mappings


Association:
Association between two or more things is refers to the state of being associated i.e. how the things
are related to each other.
Association in hibernate tells the relationship between the objects of POJO classes i.e. how the entities
are related to each other. Association or entities relationship can be unidirectional or bidirectional.
Ways of implementing association in hibernate:
Hibernate association mappings
Hibernate One-to-One Mapping using xml
Hibernate One-to-Many mapping using xml
Hibernate Many-to-One mapping using xml
Hibernate Many-to-Many mapping using xml
One To Many Mapping in Hibernate - Database Setup
We can use foreign key constraint for one to many mapping. Below is our database script for Cart
and Items table. I am using MySQL database for Hibernate one to many mapping example. setup.sql
CREATE TABLE `Cart` (
`cart_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`total` decimal(10,0) NOT NULL,
`name` varchar(10) DEFAULT NULL,
PRIMARY KEY (`cart_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

CREATE TABLE `Items` (


`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`cart_id` int(11) unsigned NOT NULL,
`item_id` varchar(10) NOT NULL,
`item_total` decimal(10,0) NOT NULL,
`quantity` int(3) NOT NULL,
PRIMARY KEY (`id`),
KEY `cart_id` (`cart_id`),
CONSTRAINT `items_ibfk_1` FOREIGN KEY (`cart_id`) REFERENCES `Cart` (`cart_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
Below is the ER diagram of the Cart and Items table.

Our database setup is


ready, let’s move on to creating hibernate One to Many Mapping example project. First of all, we will
use XML based configuration and then we will implement one to many mapping using Hibernate and
JPA annotation.
Hibernate One To Many Mapping Project Structure
Create a simple Maven project in Eclipse or you favorite IDE, the final project structure will look like

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;

public class Cart {

private long id;


private double total;
private String name;
private Set<Items> items;

public long getId() {


return id;
}
public void setId(long id) {
this.id = id;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Items> getItems() {
return items;
}
public void setItems(Set<Items> items) {
this.items = items;
}

}
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;

public class Items {

private long id;


private String itemId;
private double itemTotal;
private int quantity;
private Cart cart;

//Hibernate requires no-args constructor


public Items(){}

public Items(String itemId, double total, int qty, Cart c){


this.itemId=itemId;
this.itemTotal=total;
this.quantity=qty;
this.cart=c;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public double getItemTotal() {
return itemTotal;
}
public void setItemTotal(double itemTotal) {
this.itemTotal = itemTotal;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}

}
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;

public class HibernateUtil {

private static SessionFactory sessionFactory;

private static SessionFactory buildSessionFactory() {


try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
System.out.println("Hibernate Configuration loaded");

ServiceRegistry serviceRegistry = new


StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate serviceRegistry created");

SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

return sessionFactory;
}
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {


if(sessionFactory == null) sessionFactory = buildSessionFactory();
return sessionFactory;
}
}
Hibernate Configuration XML File
Our hibernate configuration xml file contains database information and mapping resource details.
hibernate.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 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">

<class name="Items" table="ITEMS">


<id name="id" type="long">
<column name="id" />
<generator class="identity" />
</id>
<property name="itemId" type="string">
<column name="item_id"></column>
</property>
<property name="itemTotal" type="double">
<column name="item_total"></column>
</property>
<property name="quantity" type="integer">
<column name="quantity"></column>
</property>

<many-to-one name="cart" class="Cart">


<column name="cart_id" not-null="true"></column>
</many-to-one>
</class>
</hibernate-mapping>
Notice that from items to cart, it’s many to one relationship. So we need to use many-to-one element
for cart and we are providing column name that will be mapped with the key. So based on the Cart
hibernate mapping configuration, it’s key cart_id will be used for mapping. Our project for Hibernate
One To Many Mapping Example using XML mapping is ready, let’s write a test program and check if
it’s working fine or not.
Hibernate One To Many Mapping Example - Test Program
HibernateOneToManyMain.java
package com.journaldev.hibernate.main;

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;

public class HibernateOneToManyMain {

public static void main(String[] args) {

Cart cart = new Cart();


cart.setName("MyCart");

Items item1 = new Items("I1", 10, 1, cart);


Items item2 = new Items("I2", 20, 2, cart);
Set<Items> itemsSet = new HashSet<Items>();
itemsSet.add(item1); itemsSet.add(item2);

cart.setItems(itemsSet);
cart.setTotal(10*1 + 20*2);

SessionFactory sessionFactory = null;


Session session = null;
Transaction tx = null;
try{
//Get Session
sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.getCurrentSession();
System.out.println("Session created");
//start transaction
tx = session.beginTransaction();

//Save the Model objects


session.save(cart);
session.save(item1);
session.save(item2);

//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 {

private static SessionFactory sessionFactory;

private static SessionFactory buildSessionFactory() {


try {
// Create the SessionFactory from hibernate-annotation.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate-annotation.cfg.xml");
System.out.println("Hibernate Annotation Configuration loaded");

ServiceRegistry serviceRegistry = new


StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Annotation serviceRegistry created");

SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

return sessionFactory;
}
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {


if(sessionFactory == null) sessionFactory = buildSessionFactory();
return sessionFactory;
}
}
Hibernate One To Many Mapping Annotation Model Classes
Since we don’t have xml based mapping files, all the mapping related configurations will be done
using JPA annotations in the model classes. If you understand the xml based mapping, it’s very
simple and similar. Cart1.java
package com.journaldev.hibernate.model;

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;

// Getter Setter methods for properties


}
Important point to note is the OneToMany annotation where mappedBy variable is used to define the
property in Items1 class that will be used for the mapping purpose. So we should have a property
named “cart1” in Items1 class. Don’t forget to include all the getter-setter methods. Items1.java
package com.journaldev.hibernate.model;

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;

//Hibernate requires no-args constructor


public Items1(){}

public Items1(String itemId, double total, int qty, Cart1 c){


this.itemId=itemId;
this.itemTotal=total;
this.quantity=qty;
this.cart1=c;
}
//Getter Setter methods
}
Most important point in above class is the ManyToOne annotation on Cart1 class variable and
JoinColumn annotation to provide the column name for mapping. That’s it for one to many mapping in
hibernate using annotation in model classes. Compare it with XML based configurations, you will
find them very similar. Let’s write a test program and execute it.
Hibernate One To Many Mapping Annotation Example Test Program
Our test program is just like xml based configuration, we are just using the new classes for getting
Hibernate Session and saving the model objects into database.
HibernateOneToManyAnnotationMain.java
package com.journaldev.hibernate.main;

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;

public class HibernateOneToManyAnnotationMain {

public static void main(String[] args) {

Cart1 cart = new Cart1();


cart.setName("MyCart1");

Items1 item1 = new Items1("I10", 10, 1, cart);


Items1 item2 = new Items1("I20", 20, 2, cart);
Set<Items1> itemsSet = new HashSet<Items1>();
itemsSet.add(item1); itemsSet.add(item2);

cart.setItems1(itemsSet);
cart.setTotal(10*1 + 20*2);

SessionFactory sessionFactory = null;


Session session = null;
Transaction tx = null;
try{
//Get Session
sessionFactory = HibernateAnnotationUtil.getSessionFactory();
session = sessionFactory.getCurrentSession();
System.out.println("Session created");
//start transaction
tx = session.beginTransaction();
//Save the Model object
session.save(cart);
session.save(item1);
session.save(item2);
//Commit transaction
tx.commit();
System.out.println("Cart1 ID="+cart.getId());
System.out.println("item1 ID="+item1.getId()+", Foreign Key Cart
ID="+item1.getCart1().getId());
System.out.println("item2 ID="+item2.getId()+", Foreign Key Cart
ID="+item1.getCart1().getId());

}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

Create Model Classes :


Student.java
?

package com.jwt.hibernate;

public class Student {


private long id;
private String name;
private String degree;
private String roll;
private String phone;

public long getId() {


return id;
}
public void setId(long id) {
this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getDegree() {


return degree;
}

public void setDegree(String degree) {


this.degree = degree;
}

public String getRoll() {


return roll;
}

public void setRoll(String roll) {


this.roll = roll;
}

public String getPhone() {


return phone;
}

public void setPhone(String phone) {


this.phone = phone;
}

}
Create Hibernate Mapping File :

Create student.hbm.xml file to map the Student class with the database tables.
?

<?xml version="1.0" encoding="UTF-8"?>


<!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.jwt.hibernate.Student" table="STUDENT">
<id column="ID" name="id" type="long">
<generator class="increment" />
</id>
<property column="STUDENT_NAME" name="name" type="string" />
<property column="DEGREE" name="degree" type="string" />
<property column="ROLL" name="roll" type="string" />
<property column="PHONE" name="phone" type="string" />
</class>
</hibernate-mapping>

Create Hibernate Configuration File:

Create the Hibernate configuration file (hibernate.cfg.xml) to specify database type, connection
details and the mapping files:
hibernate.cfg.xml
?

<?xml version="1.0" encoding="utf-8"?>


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.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.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>

Program to insert data :

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;

public class InsertData {

public static void main(String[] args) {

Configuration cfg = new Configuration();


cfg.configure("hibernate.cfg.xml");

SessionFactory factory = cfg.buildSessionFactory();


Session session = factory.openSession();
Student student = new Student();
student.setName("Ravi");
student.setRoll("102");
student.setPhone("8888");
student.setDegree("B.E");

Student student1 = new Student();


student1.setName("Mukesh");
student1.setRoll("103");
student1.setPhone("9999");
student1.setDegree("B.E");

Transaction tx = session.beginTransaction();
session.save(student);
session.save(student1);
System.out.println("Object saved successfully.....!!");
tx.commit();
session.close();
factory.close();
}
}

Program to retrieve data


?

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;

public class SimpleSelect {

public static void main(String[] args) {

Configuration cfg = new Configuration();


cfg.configure("hibernate.cfg.xml");

SessionFactory factory = cfg.buildSessionFactory();


Session session = factory.openSession();
Transaction tx = session.beginTransaction();

// Get All Employees


Query query = session.createQuery("from Student");
List<Student> list = (List<Student>) query.list();
for (Student st : list) {
System.out.println("List of Employees::" + st.getId() + ","
+ st.getName() + "," + st.getDegree());
}
// Get Employee with id
query = session.createQuery("from Student where id= :id");
query.setLong("id", 1);
Student stu = (Student) query.uniqueResult();
System.out.println("Student Name=" + stu.getName() + ", Degre="
+ stu.getDegree());

tx.commit();
session.close();
factory.close();
}
}

Program to update/delete data

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;

public class UpdateData {

public static void main(String[] args) {

Configuration cfg = new Configuration();


cfg.configure("hibernate.cfg.xml");

SessionFactory factory = cfg.buildSessionFactory();


Session session = factory.openSession();
Transaction tx = session.beginTransaction();

// 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);

// Delete Employee, we need to take care of foreign key constraints too


query = session.createQuery("delete from Student where id= :id");
query.setLong("id", 3);
result = query.executeUpdate();
System.out.println("Student Data Delete 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

Some of the commonly supported clauses in HQL are:

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

String hql = "FROM Employee";


Query query = session.createQuery(hql);
List results = query.list();

as clause :

as clause will allow to assign aliases to the classes.

Syntax:-
?

String hql = "FROM Employee AS E";


Query query = session.createQuery(hql);
List results = query.list();

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

String hql = "SELECT e.firstName FROM Employee e";


Query query = session.createQuery(hql);
List results = query.list();

where clause :

The where clause is used to fetch the specific objects from the database.

Syntax:-
?

String hql = "FROM Employee e WHERE e.id = 100";


Query query = session.createQuery(hql);
List results = query.list();

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

String hql = "SELECT SUM(P.salary), P.firtName FROM Person P” +


"GROUP BY P.firstName";
Query query = session.createQuery(hql);
List results = query.list();

update clause :

The UPDATE clause can be used to update one or more properties of one or more objects.

Syntax:-
?

String hql = "UPDATE Employee set salary =: salary "+


"WHERE id =:empId";
Query query = session.createQuery(hql);
query.setParameter("salary", 10000);
query.setParameter("empId", 10);
int result = query.executeUpdate();
System.out.println("Rows Affected: " + result);

DELETE clause :

The DELETE clause can be used to delete one or more objects.

Syntax:-
?

String hql = "DELETE FROM Employee "+


"WHERE id = :empId";
Query query = session.createQuery(hql);
query.setParameter("empId", 10);
int result = query.executeUpdate();
System.out.println("Rows Affected: " + result);

Insert clause :

Insert into clause of hibernate query language support where records can be inserted from one object
to another object.

Syntax:-
?

String hql = "INSERT INTO Person(firstName, lastName, salary)" +


"SELECT firstName, lastName, salary FROM old_person";
Query query = session.createQuery(hql);
int result = query.executeUpdate();
System.out.println("Rows Affected: " + result);

Aggregate Functions

avg(...), sum(...), min(...), max(...)


count(*) ,count(...), count(distinct ...), count(all...)

Subqueries

Subqueries are nothing but its a query within another query. Hibernate supports Subqueries if the
underlying database supports it.

Steps to work with HQL

Step 1 :

Write the HQL query as per requirement.For Example:


?

from Employee
Step 2 :

Obtain an instance of org.hibernate.Query by passing HQL query.For Example:


?

Query q = session.createQuery("from Employee");


Step 3 :

If the query contains parameter set those values.For Example:


?

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.list(); //for executing select queries


query.executeUpdate();//for executing update/delete queries
Step 5 : Iterate the List

we need to iterate the List collection.For Example:


?

Query q = session.createQuery("from Employee");


List<employee> empList= q.list();
for(Employee employee : empList) {
System.out.println(employee.getEmpno());
System.out.println(employee.getUserName());
</employee>

Query :

” Query ” is an interface given in org.hibernate package.If we want to execute execute an HQL


query on a database, we need to create a query object.
In order to get query object, we need to call createQuery() method in the session Interface.

Query q = session.createQuery("from Employee");

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.

Different Ways to write HQL Select query


The from Clause and Aliases

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
?

from Employee as employee

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.

Fetching Complete Object :

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
?

select * from Employee

In HQL
?

select e from Employee e


or
?

from Employee e

Fetching Partial Object :

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
?

select empid,name from Employee

Note: empid, name are the columns Employee is the table.

In HQL
?

select e.empId,e.name from Employee e

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

Hibernate Parameter Binding

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

Query query = session.createQuery("from Student where studentId = :id ");


query.setParameter("id", 5);

setString

You can use setString to tell Hibernate this parameter date type is String.
?

String hql = "from Stock s where s.stockCode = :stockCode";


List result = session.createQuery(hql)
.setString("stockCode", "1234")
.list();

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

Stock stock = new Stock();


stock.setStockCode("1234");
String hql = "from Stock s where s.stockCode = :stockCode";
List result = session.createQuery(hql)
.setProperties(stock)
.list();

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

String hql = "from Stock s where s.stockCode = ? and s.stockName = ?";


List result = session.createQuery(hql)
.setString(0, "1234")
.setParameter(1, "HUL")
.list();

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

String hql = "from Stock s where s.stockName = ? and s.stockCode = ?";


List result = session.createQuery(hql)
.setParameter(0, "HUL")
.setString(1, "1234")
.list();

Selecting fields in HQL :

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

Query query = session.createQuery("Select name from User");

List<String> names = (List<String>) query.list();

for (String n : names) {

System.out.println(n);

Selecting multiple fields in HQL

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

Query query = session.createQuery("Select id, name from User");

List<Object[]> users= (List<Object[]>)query.list();

for(Object[] user: users){

Integer id = (Integer)user[0];

System.out.println(id);

String name = (String)user[1];


System.out.println(name);
}

Hibernate One To One Mapping(XML


Mapping) Tutorial
January 1, 2015 by Mukesh Kumar at 3:47 pm

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.

Create Database and Tables :


For this example, we used MYSQL Database. Create following two tables STUDENT and
STUDENT_ADDRESS in MySQL by following sql script.

CREATE DATABASE IF NOT EXISTS `hibernate_db`


USE `hibernate_db`;

CREATE TABLE IF NOT EXISTS `student` (


`student_id` bigint(100) NOT NULL AUTO_INCREMENT,
`first_name` varchar(50) DEFAULT NULL,
`last_name` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`phone` varchar(50) DEFAULT NULL,
PRIMARY KEY (`student_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `student_address` (


`student_id` bigint(100) NOT NULL,
`address` varchar(100) DEFAULT NULL,
`city` varchar(100) DEFAULT NULL,
`state` varchar(100) DEFAULT NULL,
`country` varchar(100) DEFAULT NULL,
PRIMARY KEY (`student_id`),
CONSTRAINT `FK_student_address_student` FOREIGN KEY (`student_id`)
REFERENCES `student` (`student_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Directory Structure of Project :


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.
Create Model Classes :
Create two Pojo classes Student.java and StudentAddress.java to model the two tables
STUDENT and STUDENT_ADDRESS, respectively.

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.

Hibernate Utility Class :


Create a utility class for creating Hibernate SessionFactory.

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

Create Hibernate Mapping Files :


Create two XML files student.hbm.xml and studentaddress.hbm.xml to map the JavaBean
classes with the database tables.

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

Create Hibernate Configuration File:


Create the Hibernate configuration file (hibernate.cfg.xml) to specify database type,
connection details and the mapping files:

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.

Create a Test Program :


Following is code of the test program that persists some sample data.

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 :

Result in the STUDENT table:

Result in the STUDENT_ADDRESS table:

Hibernate One-to-Many XML Mapping


Example
Oct 17, 2014 by Mukesh Kumar at 3:47 pm

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

CREATE TABLE `BANK` (


`bank_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`bank_name` VARCHAR(50) NOT NULL DEFAULT '0',
PRIMARY KEY (`bank_id`)
);

CREATE TABLE `CUSTOMER` (


`customer_id` BIGINT(10) NOT NULL AUTO_INCREMENT,
`firstname` VARCHAR(50) NULL DEFAULT NULL,
`lastname` VARCHAR(50) NULL DEFAULT NULL,
`birth_date` DATE NULL DEFAULT NULL,
`cell_phone` VARCHAR(15) NULL DEFAULT NULL,
`bank_id` BIGINT(20) NULL DEFAULT NULL,
PRIMARY KEY (`customer_id`),
INDEX `FK_DEPT` (`bank_id`),
CONSTRAINT `FK_BANK` FOREIGN KEY (`bank_id`) REFERENCES `bank`
(`bank_id`)
);

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.

Create Model Classes :


Create two Pojo classes Bank.java and Customer.java to model the two tables BANK and
CUSTOMER, respectively.

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

Hibernate Utility Class :


Create a utility class for creating Hibernate SessionFactory.

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

Create Hibernate Mapping Files :


Create two XML files bank.hbm.xml and customer.hbm.xml to map the JavaBean classes
with the database tables.

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

Create Hibernate Configuration File:


Create the Hibernate configuration file (hibernate.cfg.xml) to specify database type,
connection details and the mapping files:

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.

Create a Test Program :


Following is code of the test program that persists some sample data.

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 :

Result in the BANK table:

Result in the CUSTOMER table:

One table per class hierarchy


Suppose we have following class hierarchy.We have Employee class as base class and
permanentEmployee and ContractEmployee as derived class. permanentEmployee and
ContractEmployee inherit from Employee class.

 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

Let us create Java classes for the above hierarchy.

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.

<discriminator> tag is used to define the discriminator column.

<subclass> tag is used to map the subclass ContractEmployee and PermanentEmployee.

The discriminator-value for PermanentEmployee is defined as “PE” and that for


ContractEmployee is defined “CE”, Thus, when Hibernate will persist the data for
PermanentEmployee or ContractEmployee it will accordingly populate this value.

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

Directory Structure of the Project


Output
When you run it,you will get following output in the eclipse console.
SQL Output

CRUD Operations Using Hibernate 3


March 9, 2014 by Mukesh Kumar at 3:47 pm

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;

CREATE TABLE `empcrud` (


`ID` int(11) NOT NULL,
`NAME` varchar(255) NOT NULL,
`SAL` int(11) NOT NULL,
`CITY` varchar(255) NOT NULL,
`PHONE` int(11) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 Hibernate Tutorial
 Hibernate Basics
 Hibernate Inheritance Mapping
 Hibernate Query Language (HQL)
 Composite Primary Keys In Hibernate

Step 1: Create a Java project


Create a Java project and update Hibernate jars and hibernate related jar in to build path of
your project.Download Hibernate Jar from Here

Directory Structure of Project


Step 2 : Create the Persistent class

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 

13    public int getId() {


        return id;
14
    }
15
 
16
    public void setId(int id) {
17
        this.id = id;
18
    }
19
 
20    public String getName() {

21        return name;

22    }

23 

24    public void setName(String name) {

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 

35    public String getCity() {

36        return city;

37    }

38 

39    public void setCity(String city) {


        this.city = city;
40
    }
41
42

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

Step 3 : Create Hibernate config file (hibernate.cfg.xml)

hibernate.cfg.xml

1 <?xml version="1.0" encoding="utf-8"?>


<!DOCTYPE hibernate-configuration PUBLIC
2
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
3
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
4
 
5
<hibernate-configuration>
6
    <session-factory>
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="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         <mapping resource="com/jwt/hibernate/Employee.hbm.xml" />


5     </session-factory>

1 </hibernate-configuration>
6

1
7

Step 4 : Create mapping file for Employee class

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

7         <id name="id" type="integer" column="ID">

8             <generator class="increment" />

9         </id>

10        <property name="name" type="string" column="NAME" not-null="true" />


        <property name="sal" type="integer" column="SAL" not-null="true" />
11
        <property name="city" type="string" column="CITY" not-null="true" />
12
        <property name="phone" type="integer" column="PHONE"
13
            not-null="true" />
14
    </class>
15</hibernate-mapping>

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 {

10            sessionFactory = new Configuration().configure()

11                    .buildSessionFactory();

12        } catch (Throwable ex) {

13            System.err.println("SessionFactory creation failed" + ex);


            throw new ExceptionInInitializerError(ex);
14
        }
15
    }
16
 
17
    public static SessionFactory getSessionFactory() {
18
        return sessionFactory;
19    }

20}

21

Step 6 : Create Main Class for database operation(CRUD)

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  

12 public class Main {

13     public static void main(String[] args) {

14         Main main = new Main();

15         main.saveEmployee("Mukesh", "CEO", 100000, 893965);


        main.saveEmployee("Ravi", "Manager", 50000, 996654);
16
        main.saveEmployee("Amit", "PM", 45000, 93445);
17
        main.retriveEmployee();
18
        main.deleteEmployee();
19
        main.updateEmployee();
20     }

21  

22     public void saveEmployee(String name, String city, int sal, int phone)
{
23
        Session session =
24 HibernateUtil.getSessionFactory().openSession();

25         Transaction transaction = null;

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();

50         Transaction transaction = null;

51         try {

52             transaction = session.beginTransaction();
            List employee = session.createQuery("from Employee").list();
53
 
54
            for (Iterator iterator = employee.iterator();
55 iterator.hasNext();) {

56                 Employee employee1 = (Employee) iterator.next();

57                 System.out.println(employee1.getName() + "  "

58                         + employee1.getCity() + "  " + employee1.getSal()


                        + "   " + employee1.getPhone());
59
            }
60
            transaction.commit();
61
 
62
63         } catch (HibernateException e) {

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);

84             Employee employee = (Employee) query.uniqueResult();

85             session.delete(employee);

86             System.out.println("Employee records deleted!");

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             String queryString = "from Employee where sal = :sal";


4             Query query = session.createQuery(queryString);

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

Look and Feel :


We have used css and images to make pages attractive. After completion of this tutorial you
will easily understand how css and images should be used in java based web application.
For creating the web application, we used JSP for presentation logic, Servlet class for
controller layer and hibernate for database access codes.

Tools and Technologies :


 JDK 1.6
 Hibernate 3.6.3.Final
 Eclipse
 MySQL 5.5.
 Tomcat 6.0

Directory structure of the project :

Directory Structure of the project is given bellow.


Create database table for storing data :
SQL query is given below.Execute the following query in mysql database.

CREATE TABLE `jwt`.`USER_TABLE` (


`id` DOUBLE NOT NULL AUTO_INCREMENT,
`firstName` VARCHAR(45) NOT NULL DEFAULT '',
`middleName` VARCHAR(45) NOT NULL DEFAULT '',
`lastName` VARCHAR(45) NOT NULL DEFAULT '',
`email` VARCHAR(45) NOT NULL DEFAULT '',
`userId` VARCHAR(45) NOT NULL DEFAULT '',
`password` VARCHAR(45) NOT NULL DEFAULT '',
PRIMARY KEY(`id`)
)
ENGINE = InnoDB;

For creating the application in Eclipse, follow the steps mentioned below.

Step 1 : Create Dynamic Web Project :


Open eclipse IDE,and go toFile -> New -> Project -> and select Dynamic Web
Project,specify the project name as "MVCApplication" and click on next -> finish .
Step 2 : Add Jar files for hibernate and mysql :
Copy all the jar files as shown below inside lib folder of the project
Step 3 : Creating web pages :
Now let us create jsp files inside Web-Content folder of your project.

login.jsp
?

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2
<html xmlns="http://www.w3.org/1999/xhtml">
3
<head>
4
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
5
<title>Login Page</title>
6 <link href="css/style.css" rel="stylesheet" type="text/css" />

7 </head>

8 <body>

9 <form method="post" action="LoginServlet">

10<div style="padding: 100px 0 0 250px;">


<div id="login-box">
11
<h2>Login Page</h2>
12
Please provide your credential to use this website
13
<br>
14
<br>
15<div id="login-box-name" style="margin-top:20px;">User Id:</div>

16<div id="login-box-field" style="margin-top:20px;">

17<input name="userId" class="form-login" title="Username" value="" size="30"


maxlength="50" />
18
</div>
19
<div id="login-box-name">Password:</div>
20
<div id="login-box-field">
21
<input name="password" type="password" class="form-login" title="Password"
22value="" size="30" maxlength="48" />

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;

6 text-align: center; text-decoration: underline }

7 table{font-family: Calibri; color:white; font-size: 11pt; font-style:


normal;width: 50%;
8
text-align:; background-color: SlateBlue; border-collapse: collapse;
9 border: 2px solid navy}
table.inner{border: 0px}
10
</style>
11
</head>
12
<body>
13
<h3>Student Registration Form</h3>
14<form action="RegisterServlet" method="POST">

15<table align="center" cellpadding = "10">

16<tr>

17<td>First Name</td>

18<td><input type="text" name="firstName" maxlength="30"/>


(max 30 characters a-z and A-Z)
19</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>

28<td><input type="text" name="lastName" maxlength="30"/>

29(max 30 characters a-z and A-Z)


</td>
30
</tr>
31
<tr>
32
<td>Email</td>
33
<td><input type="text" name="email" maxlength="100" /></td>
34</tr>

35<tr>

36<td>User ID</td>

37<td><input type="text" name="userId" maxlength="100" /></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">

44<input type="submit" value="Submit">

45<input type="reset" value="Reset">

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>

8      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

9      <link rel="stylesheet" type="text/css" href="css/style.css"/>

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

18                 User user = (User) session.getAttribute("user");

19             %>     

20             <b>Welcome <%= user.getFirstName() + " " +


user.getLastName()%></b>     
21
             <br/>
22             <a href="logout.jsp">Logout</a>
23         </p>

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
?

1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"


    pageEncoding="ISO-8859-1"%>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
3 "http://www.w3.org/TR/html4/loose.dtd">
4
<html>
5
<head>
6
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7 <title>Error Page</title>

8 </head>

9 <body>

10<center>

11     <h1>Your Login Was Unsuccessful - Please Try Again</h1>


     To login again <a href="login.jsp">click here</a>.
12
</center>
13
</body>
14
</html>
15

Step 4 : Create css file


Create a folder css inside WebContent of the project. Now create a css file style.css inside
this folder and add below code into this file.

style.css
?

1 body{

2 font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial,


Helvetica, sans-serif;
3 font-size:12px;
4 }
5 p, h1, form, button{border:0; margin:0; padding:0;}

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;

45 border:solid 1px burlywood;


width:200px;
46
margin:2px 0 20px 10px;
47
border-radius: 5px;
48
}
49
#container button{
50 clear:both;

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 }

61 table, tr, td{

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;

71     padding: 58px 76px 0 76px;

72     color: #ebebeb;

73     font: 12px Arial, Helvetica, sans-serif;

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;

85     font: bold 44px "Calibri", Arial;

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     border: 1px solid #0d2c52;


5     background-color:#1e4f8a;

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

Step 5 : Creating hibernate Model Class :


Create a package com.javawebtutor.model and create a java class User in this package and
add following code in this class.

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;

13    private String firstName;

14    private String middleName;

15    private String lastName;

16    private String email;

17    private String userId;


    private String password;
18
 
19
    public User() {
20
    }
21
 
22
     
23
    public User(String firstName, String middleName, String lastName,
24String email, String userId, String password) {

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 

45    public void setFirstName(String firstName) {

46        this.firstName = firstName;

47    }

48 

49    public String getMiddleName() {


        return middleName;
50
    }
51
 
52
    public void setMiddleName(String middleName) {
53
        this.middleName = middleName;
54
    }
55
 
56
    public String getLastName() {
57        return lastName;

58    }

59 

60    public void setLastName(String lastName) {

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 

78    public void setUserId(String userId) {

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

Step 5 : Creating hibernate Model Class :


User.java

This is a simple bean class representing the Persistent class in hibernate.


Create a package com.jwt.hibernate.bean,in this package create java class User.java and add
following code in this class.

1 package com.jwt.hibernate.bean;

2  

3 public class User {


    private int id;
4
    private String userName;
5
    private String password1;
6
    private String email;
7
    private String phone;
8     private String city;

9
 
10    public int getId() {

11        return id;

12    }

13 

14    public void setId(int id) {

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 

25    public String getPassword1() {

26        return password1;

27    }

28 
29

30

31    public void setPassword1(String password1) {

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 

42    public String getPhone() {

43        return phone;

44    }

45 

46    public void setPhone(String phone) {


        this.phone = phone;
47
    }
48
 
49
    public String getCity() {
50
        return city;
51
    }
52
 
53    public void setCity(String city) {

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             System.err.println("Initial SessionFactory creation failed." +


3 ex);

1             throw new ExceptionInInitializerError(ex);


4         }

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

Step 6 : Create the Configuration file :


The configuration file contains informations about the database and mapping file.
Conventionally, its name should be hibernate.cfg.xml .Configuration file must be in classpath
of your Project.Place this file in src of your project by default it will added to classpath of
your project.

hibernate.cfg.xml
?

1 <?xml version="1.0" encoding="UTF-8"?>

2 <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate


Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-
3 configuration-3.0.dtd">

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

Step 7 : Create Controller class


Here we are going to create two classes LoginServlet and RegisterServlet which will help
interaction between view layer, and business service classes.LoginSrvlet will control login
request and RegisterServlet will control /new user registration process.

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 {

13    public void doPost(HttpServletRequest request, HttpServletResponse


response)
14
            throws ServletException, IOException {
15
 
16
     String userId = request.getParameter("userId");   
17
     String password = request.getParameter("password");
18     LoginService loginService = new LoginService();

19     boolean result = loginService.authenticateUser(userId, password);

20     User user = loginService.getUserByUserId(userId);

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 

13public class RegisterServlet extends HttpServlet {

14    public void doPost(HttpServletRequest request, HttpServletResponse


response)
15
            throws ServletException, IOException {
16
     response.setContentType("text/html;charset=UTF-8");
17     PrintWriter out = response.getWriter();

18     String firstName = request.getParameter("firstName");


19     String middleName = request.getParameter("middleName");

20     String lastName = request.getParameter("lastName");


     String email = request.getParameter("email");
21
     String userId = request.getParameter("userId");
22
     String password = request.getParameter("password");
23
     User user = new User(firstName,middleName,lastName, email,userId,
24password);

25             

26     try { 

27         RegisterService registerService = new RegisterService();


         boolean result = registerService.register(user);      
28
         out.println("<html>");
29
         out.println("<head>");      
30
         out.println("<title>Registration Successful</title>");    
31
         out.println("</head>");
32         out.println("<body>");

33         out.println("<center>");

34         if(result){

35             out.println("<h1>Thanks for Registering with us :</h1>");

36             out.println("To login with new UserId and Password<a


href=login.jsp>Click here</a>");
37         }else{

38             out.println("<h1>Registration Failed</h1>");

39             out.println("To try again<a href=register.jsp>Click


here</a>");
40
         }
41
         out.println("</center>");
42
         out.println("</body>");
43         out.println("</html>");

44     } finally {       

45         out.close();

46     }

47}

48 
}
49
50

51

Step 8 : Create Service class for Business logic


Create two classes LoginService and RegisterService.These classes will interact with model
layer for business processing.

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 

13    public boolean authenticateUser(String userId, String password) {

14        User user = getUserByUserId(userId);         

15        if(user!=null && user.getUserId().equals(userId) &&


user.getPassword().equals(password)){
16
            return true;
17        }else{

18            return false;

19        }

20    }

21 

22    public User getUserByUserId(String userId) {


23        Session session = HibernateUtil.openSession();

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();

11     if(isUserExists(user)) return false;  

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) {

20         if (tx != null) {


             tx.rollback();
21
         }
22
         e.printStackTrace();
23
     } finally {
24
         session.close();
25     } 

26     return true;

27}

28 

29public boolean isUserExists(User user){

30     Session session = HibernateUtil.openSession();


     boolean result = false;
31
     Transaction tx = null;
32
     try{
33
         tx = session.getTransaction();
34
         tx.begin();
35         Query query = session.createQuery("from User where

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

Step 9: Create web.xml file :


Create web.xml file inside WEB-INF directory of project.

web.xml

1 <?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2
xmlns="http://java.sun.com/xml/ns/javaee"
3 xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
4 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID"

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>

Run the Application :


To run the application, right click on the project then Run as -> Run On Server select Tomcat
-> Next ->Finish.

Output in Browser :

Login Page
New User Registration Page

Welcome Page

Error Page
Result Page

You might also like