You are on page 1of 16

Hibernate

_______________________________________________________________________________
Hibernate is ORM tool of Java which is used for connect your java application with database application
Same like as JDBC

Q. what is ORM?
______________________________________________________________________
ORM stands for object relationship mapping basically it is design pattern where class consider as table
in database , class every field consider as column in database table and class object consider as row in
database table called as ORM.

Q. Why uses hibernate if we have JDBC already?


__________________________________________________________________________
1. Hibernate is database independent tool means if write query using HQL i.e Hibernate Query language
it is common to all database means we not need to perform any change in syntax if we change the
backend database of application means suppose if we connect with Mysql database and if we change
mysql to oracle and if your application connected by using hibernate we not need to perform change in
query syntax just we need to perform change in XML configuration file
if we connect your application using JDBC means in backend we need to SQL query but SQL query syntax
little bit different database to database so when we work with JDBC and if you want to change database
of application then it is very complicated

2. Hibernate create database table automatically programmer not need to create table manually as
well as in hibernate every table must have primary key but if we think about JDBC programmer need to
create table manually or need to write external logic in java code for table creation using JDBC DDL
command.

3. Hibernate provide easy support to joins means programmer not need to know the join syntax in
hibernate it is internally manageable by ORM
4. Hibernate provide easy or better implementation of relationship between table like as one to many or
many to one etc

5. Hibernate provide cache level support means first level cache or second level cache so it help us to
increase the perform of application
etc

How to Create Application in Hibernate?


________________________________________________________________________________
if we want to create application in hibernate we have some important steps.

1. Create Maven Project


___________________________________________________________
file --- new --- other --- maven --- create maven project ---create maven project and select (skip
archtype selection checkbox) --- click on next button – give group id and artifact id.
Once we create hibernate application we get following folder structure

2. Add the Following maven dependencies


____________________________________________________________________________________
If we think about hibernate we required to add two maven dependencies.
a. hibernate core maven dependency
b. mysql connector maven dependency

<dependencies>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>

3. Create POJO class


___________________________________________________________________________
We want to create class name as Employee with field id, name and salary

package org.techhub;
public class Employee {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSal() {
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
private int sal;
}

4. Map your pojo class with database


____________________________________________________________________________
When we map your POJO class with database table then it is called as entity class
There are two ways to map your POJO class with database table
____________________________________________________________________________________
a) Using XML
____________________________________________________________
When we want to configure your POJO as Entity class with database table using XML we have
following steps.

i) Create XML file under src/main/resources folder same name as pojo class name with
.hbm.xml extension

Right click on folder --- select --- other --- xml --- give filename classname.hbm.xml

ii) Write the DOC type in XML Mapping file


_________________________________________________________________________
if we want to write doctype we have the following steps.

select maven dependency --- select hibernate-core.jar file ---- select org.techhub package --- open
file ---- hibernate-mapping.dtd file --- select doctype from XML commented part and paste in mapping
file

<!DOCTYPE hibernate-mapping PUBLIC


"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

Once we write the doctype then you can write mapping tags in XML file for map your pojo class as
entity class with database.

iii) Write the following tags for map your pojo class as database table.
_____________________________________________________________________________
if we want to map your POJO class with database table then we required to write following tags

<hibernate-mapping>
<class name=”classname” table=”tablename”>
<id name=”fieldname” column=”columnname”/>
<property name=”name” column=”columnname”/>
</class>
</hibernate-mapping>
Note: if we think about above code we have tags <hibernate-mapping> this tag indicate we want to
write mapping between class and table.

<class name=”classname” table=”tablename”> : this tag indicate we decide which class map with
which table.
<class indicate the mapping between class and table name=”classname” indicate the class which we
want to map table=”tablename” indicate decide which table we want to map with class.
when we not provide the tablename then hibernate container by default create table same as
classname

<id name=”fieldname” column=”columnname”/>: here id attribute indicate the primary key


name=”fieldname” property or attribute decide which field map with which column

<property name=”name” column=”columnname”/>: property name=”fieldname” this attribute decide


which field map with which column but property indicate non primary key column

Example:

b) Using Annotation: if we want to configure your POJO class as entity class using annotation we
have some important annotation given below.

@Entity: this annotation indicate the class


@Table: this annotation indicate table name which we want to map with class
@Id: Id indicate the primary key column name
@Column: indicate the column name which we want to specify in table this annotation can work with
@Id annotation as well as without @Id annotation means @Id and @Column with field means field
work as primary key shown in following diagram
5. Write XML configuration file :
In the case of hibernate if we want to configure your database credential and hibernate database
configuration you have to write XML file with extension .cfg.xml Example: hibernate.cfg.xml

Steps to write configuration file for hibernate


____________________________________________________________________________________
a). Create hibernate.cfg.xml file under src/java/resource folder.
b) Write doctype for configuration file

Steps to write doctype for configuration file


______________________________________________________________________________
Open maven dependencies --- open hibernate-core.jar file ---- open package org.hibernate ----
hibernate-configuration.dtd --- copy the doc type from commented part of application and paste in xml
file
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

c) Write the following tags for writing database configuration

<hibernate-configuration>
<session-factory>
<!-- Related to the connection START -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/mysql</property>
<property name="connection.user">root</property>
<property name="connection.password">root</property>
<!-- Related to the connection END -->
<!-- Related to hibernate properties START -->
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">create</property>
<!-- Related to hibernate properties END-->
<mapping resource="employee.hbm.xml"/>
<!-- Related to the mapping END -->
</session-factory>
</hibernate-configuration>

<!-- Related to the connection START -->


<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/mysql</property>
<property name="connection.user">root</property>
<property name="connection.password">root</property>
____________________________________________________________________
These tags help us to writing database configuration

<property name="show_sql">true</property>: this tag indicate show the sql query generated by
hibernate
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>: this tag indicate we have
dialect class name and dialect class help us to generate the SQL Syntax as per the database means if we
have MYSQL dialect class then dialect generate the SQL syntax for MYSQL and if we have oracle
database and if we write the dialect class for oracle then dialect generate the SQL syntax for oracle.

<property name="hbm2ddl.auto">create/alter/drop/update</property> : this property indicate you


can create database table automatically by hibernate hbm2ddl.auto indicate hibernate to data definition
language means if we use update with hbm2ddl.auto means hibernate can create table if not exist and if
table is exist then update it.
if we use create and if table not present then hibernate create new and if table present then hibernate
delete the previous table

<mapping resource="employee.hbm.xml"/>: mapping resource indicate you map here xml configuration
file which we configure between class and table.

6. Write DAO class


DAO stands for data access object or it is repository class where we write all database logics
If we want to write DAO class we have some following steps.

1) Add org.hibernate and org.hibernate.cfg.* package


_____________________________________________________________________
import org.hibernate.*;
import org.hibernate.cfg.*;

2) Create reference of Configuration class and call the configuration file


_____________________________________________________________________________
if we want to call the configuration file we have Configuration class and its configure() method so we
required to create its object call configuration file

Syntax: Configuration ref = new Configuration();


ref.configure(“filename);

3) Create reference of SessionFactory


__________________________________________________________________
SessionFactory is hibernate container which is responsible for creating session , maintain the second
level cache and other overall activity of hibernate called as hibernate container
if we want to create reference of SessionFactory we have method name as buildSessionFactory() of
Configuration class and this method return reference of SessionFactory to us
Syntax:
SessionFactory ref = configure.buildSessionFactory();
Sample code
4) Create Reference of Session interface
_____________________________________________________________________________________
Session means when we establish the connection between java application and database using
hibernate called as session means in short when we establish the connection with database called as
session and if we want to create reference of Session we have method name as openSession() and it is
method of SessionFactory and return reference of Session

Syntax: Session ref= factoryref.openSession();

package org.techhub;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class ConfigApp {
public static void main(String[] args) {
Configuration cfg= new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf=cfg.buildSessionFactory();
Session sesession=sf.openSession();
}
}
Once we create reference of Session you can create reference of Transaction
Q. what is Transaction?
________________________________________________________________________
Transaction means task perform between particular session called as Transaction
means support consider if we open session means we establish connection with database and if we
insert record in table or delete record from database table or update record in table called as
transaction
Syntax: Transaction ref = sessionref.beginTransaction();
Once we create reference of Transaction you have to create object of POJO class or entity class and
store data in it and store entity class in database using session method

Once we create object of POJO class after that you can work with database means can store object as
row in database table, delete object as row from database etc and for that purpose session provide
some inbuilt method to us

Methods of Session
____________________________________________________________________________________
void save(Object): this method help us to store object as row in database table.
void delete(Object): this method help us delete object as row from database table.
void update(Object): this method help us to update database record as row
Object load(POJOclassname.class,Object key): this method help us to fetch data from database table
using its key
void saveOrUpdate(Object): this method can update record if exist if not then create new record

Now we want to save the Employee object as row in database table for that we have save() method of
Session
Source code
package org.techhub;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class ConfigApp {
public static void main(String[] args) {
Configuration cfg= new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf=cfg.buildSessionFactory();
Session session=sf.openSession();
Transaction t=session.beginTransaction();
Employee e1 = new Employee();
e1.setId(1);
e1.setName("ABC");
e1.setSal(10000);
session.save(e1);
t.commit();
session.close();
}
}

How to delete record from database table


__________________________________________________________________
If we want to delete record from database table we have delete() method of Session just you have to
pass object with primary key which we want to delete
package org.techhub;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class ConfigApp {
public static void main(String[] args) {
Configuration cfg= new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf=cfg.buildSessionFactory();
Session session=sf.openSession();
Transaction t=session.beginTransaction();
Employee e1 = new Employee();
e1.setId(1);
session.delete(e1);
t.commit();
session.close();
}
}
If we want to update record of database table using hibernate we have update method just you have to
create object of class and pass primary key value with object and update recorod so you can change
other field of object but cannot change primary key
package org.techhub;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class ConfigApp {
public static void main(String[] args) {
Configuration cfg= new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf=cfg.buildSessionFactory();
Session session=sf.openSession();
Transaction t=session.beginTransaction();
Employee e1 = new Employee();
e1.setId(4);
e1.setName("STV");
e1.setSal(70000);
session.saveOrUpdate(e1);
t.commit();
session.close();
}
}

Object load(POJOclassname.class, Object key): this method help us to fetch record from database table
using its primary key and row in the form of Object and if key not present return exception
package org.techhub;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class ConfigApp {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session session = sf.openSession();
Transaction t = session.beginTransaction();
try {
Object obj = session.load(Employee.class, new Integer(30));
if (obj != null) {
Employee e = (Employee) obj;
System.out.println(e.getId() + "\t" + e.getName() + "\t" + e.getSal());
} else {
System.out.println("Object not found");
}
} catch (ObjectNotFoundException ex) {
System.out.println("Record Not Found");
}
t.commit();
session.close();
}
}
HQL
____________________________________________________________
HQL stands for Hibernate Query Language it is object oriented version of SQL means we write the
database query using HQL same like as SQL
The major difference between HQL and SQL is HQL is database independent language and SQL syntax
are vary from database to database and in the case of SQL we use table in query but in the case of HQL
we class as replacement of table

Example using SQL


select *from employee ; here employee is table in database

Example using HQL


from Employee e; //here we use class as replacement of table

Example using SQL

select name,email,contact from employee ; here name,email and contact are the columns and
employee is table

Example using HQL


select e.name,e.email,e.contact from Employee e; //here e.name ,e.email and e.contact are the
field of Employee class and Employee is class name as replacement of table and e is reference of
Employee class.

How to execute HQL Query using Hibernate


__________________________________________________________________________________
if we want to execute HQL query using hibernate we have to use following steps.

1. add the org.hibernate.* and org.hibernate.cfg.* package in application


import org.hibernate.*;
import org.hibernate.cfg.*;
2. Create reference of Query interface
________________________________________________________________________
Query is interface from org.hibernate.query.* package which is used for execute the all DDL and DML
command using hibernate so if we want to create reference of Query interface we have to use
createQuery() method of session . In short we can say Query work as PreparedStatement interface

Syntax: Query ref = session.createQuery(String hqlStatement);


3. Use its executeUpdate() and list() method
______________________________________________________________________________
Query interface provide two methods to us

List list(): this method help us to execute the select query and fetch row as object and store in list
collection
int executeIUpdate(): this method help us to execute the all DDL and DML statement except select and
if statement executed successfully return 1 otherwise return 0

Now we want to create program fetch employee table data using HQL
______________________________________________________________________________
Note: if we think about above code we use wild card selection technique means fetch complete column
data from row

How to execute the partial select query using HQL


__________________________________________________________________________________
means we want to fetch particular column from row of database table means suppose consider we have
Employee class with three field id,name and sal means with three column so we want to fetch only
name and salary of employee not id from row So here we required to use partial selection technique.
means fetch particular column so you can write your HQL Query like as

Syntax: select ref.fieldname,ref.fieldname from classname ref;

Note: when we fetch particular column from database table then we get data in collection in the form of
Object class array because we not fetch complete object just fetch some field of object means we try to
multiple data with different data type so this is major reason we get data in the form of Object class
array and stored in list collection .

Example: we want to fetch name and salary of employee


How to pass parameter to HQL query
________________________________________________________________________
if we want to pass parameter to HQL Query we have to use label concept and we have one inbuilt
method name as setParameter() of Query interface

Example: we want to fetch name and salary of employee using its id.

Query q=session.createQuery("select e.name,e.sal from Employee e where e.id:=empid");


if we think about this statement we have e.id:=empid here empid is label which we use in
setParameter() as parameter to HQL Query

package org.techhub;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
public class HQLAPP {
public static void main(String[] args) {
// TODO Auto-generated method stub
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf=cfg.buildSessionFactory();
Session session=sf.openSession();
Transaction t=session.beginTransaction();
Query q=session.createQuery("select e.name,e.sal from Employee e where
e.id=:empid");
q.setParameter("empid",2);
List<Object[]> list=q.list();
for(Object []o:list) {
System.out.println(o[0]+"\t"+o[1]);
}

You might also like