Hibernate 3
Hibernate 3
_______________________________________________________________________________
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.
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
<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>
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;
}
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
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
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
Example:
b) Using Annotation: if we want to configure your POJO class as entity class using annotation we
have some important annotation given below.
<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>
<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.
<mapping resource="employee.hbm.xml"/>: mapping resource indicate you map here xml configuration
file which we configure between class and table.
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();
}
}
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
select name,email,contact from employee ; here name,email and contact are the columns and
employee is table
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
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 using its id.
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]);
}