SlideShare a Scribd company logo
Hibernate
Introduction to Hibernate.
Hibernate was started in 2001 by Gavin King as an alternative
to EJB2
Hibernate simplifies the development of java application.
C,C++,Java,etc.. Are programming languages.
JDBC,SERVLET,JSP,etc…are technologies.
Hibernate,Spring,etc..are framework.
ORM-Object Relational Mapping
ORM is a programming technique which is used to convert
object into a relational database.
Java Objects Directly Mapping
Relational
DB
Object Mapping Relational
Continues….
ORM framework is Hibernate.
Hibernate is an ORM tool which means it is used to map plain
java objects to tables of a relational database and vice-versa.
Your
Application ORM-Middleware acting as
a bridge between
application and DB
DB
The “CRUD” Operations handover the object to Hibernate.
Hibernate use JDBC internally to talk to the relational database
for persisting.
For ex: Student Class
Name
RollNo
Address
Mobile
Table name:Student_Info
Name RollNo Address Mobile
Student student=new
student(“Anu”,”1”,”ABCD”,”9852xxxx”);
In the above example if we are using JDBC,the programmer
need to write a lengthy code.
Instead, if we are using Hibernate, programmer want just to
pass the java object which you want to store and persist
implicitly and will generate optimized query and are stored data
into table.
If we are using hibernate the code will be like this:
public void insert Student_Info(Student student)
{
Session session=factory.openSession();
Transaction tx=null;
try{
tx=session.beginTransaction();
Session.save(student);
tx.commit();}
Catch(Hibernate Exception e){if(tx!=null)tx.rollback();
e.PrintStackTrace();
}Finally
{session.close();}}
In JDBC retrieval of data is performed by using result set.It
will be little bit difficult for the programmer to write the code.
In Hibernate,the code will be like this:
List Student_InfoList=Session.createQuery(“FROM Student_Info”).list();
Advantages of using Hibernate:
Faster retrieval of data.
• Can retrieve data only in a single line of code in hibernate.
Opening and closing of DB connection would no longer be a
problem.
• Some times the programmer forget to close the connection, they will lead to memory
leak problems. But Hibernate will do it implicitly.
Do not bother about change in a column of a table need only to
change in one place in XML file or java annotation in java model
object.
• Changing Mobile to Phone No:
Hibernate Architecture
Hibernate is a ORM framework that is built on the top of
multiple technologies like JDBC,JNDI(Java Naming Directory
Interface),JTA(Java Transaction API) etc…to develop object
based ORM mapping persistence logic as a db software
independent persistence logic.
Hibernate is a framework, it does not interact directly with db.
•JAVA uses i/p in the form of objects.
•Hibernate give o/p to application in the form of objects.
•Hibernate take support of one or more technologies to interact
with db through JDBC driver.
•Once persistence operations is done in db s/w results goes to
hibernate framework through JDBC driver and JTA.
Hibernate ppt
Following section gives brief description of each of the class
objects involved in Hibernate Application Architecture.
Configuration Object
•The Configuration object is the first Hibernate object you create
in any Hibernate application.
•It is usually created only once during application initialization.
It represents a configuration or properties file required by the
Hibernate.
The Configuration object provides two keys components −
Database Connection − This is handled through one or more
configuration files supported by Hibernate. These files are
hibernate.properties and hibernate.cfg.xml.
Class Mapping Setup − This component creates the
connection between the Java classes and database tables.
Class objects in hibernate Continues….
SessionFactory Object
• The SessionFactory is a heavyweight object; it is usually created during
application start up and kept for later use.
• You would need one SessionFactory object per database using a separate
configuration file. So, if you are using multiple databases, then you
would have to create multiple SessionFactory objects.
Class objects in hibernate Continues….
Session Object
•The Session object is lightweight and designed to be instantiated
each time an interaction is needed with the database.
•The session objects should not be kept open for a long time
because they are not usually thread safe and they should be
created and destroyed them as needed.
Class objects in hibernate Continues….
Transaction Object
•This is an optional object and Hibernate applications may
choose not to use this interface
•Transactions in Hibernate are handled by an underlying
transaction manager and transaction (from JDBC or JTA).
Class objects in hibernate Continues….
Query Object
•Query objects use SQL or Hibernate Query Language (HQL)
string to retrieve data from the database and create objects.
Class objects in hibernate Continues….
Criteria Object
•Criteria objects are used to create and execute object
oriented criteria queries to retrieve objects.
Hibernate - Mapping Files
An Object/relational mappings are usually defined in an XML document. This
mapping file instructs Hibernate — how to map the defined class or classes to the
database tables?
Consider an ex:
create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL, PRIMARY KEY (id) );
Based on the two above entities, we can define following mapping file,
which instructs Hibernate how to map the defined class or classes to the
database tables.
<?xml version = "1.0" encoding = "utf-8"?>---
<hibernate-mapping>
<class name = "Employee" table = "EMPLOYEE">
<meta attribute = "class-description">
This class contains the employee detail.
</meta>
<id name = "id" type = "int" column = "id"> <generator class="native"/>
</id>
<property name = "firstName" column = "first_name" type = "string"/>
<property name = "lastName" column = "last_name" type = "string"/>
<property name = "salary" column = "salary" type = "int"/>
</class>
</hibernate-mapping>
You should save the mapping document in a file with the format
<classname>.hbm.xml.
Here,We saved our mapping document in the file
Employee.hbm.xml.
Let us see understand a little detail about the mapping elements
used in the mapping file −
1. The mapping document is an XML document having <hibernate-
mapping> as the root element, which contains all the <class>
elements.
2.The <class> elements are used to define specific mappings from a Java
classes to the database tables.
3. The <meta> element is optional element and can be used to create the
class description.
4. The <id> element maps the unique ID attribute in class to the primary
key of the database table.
5. The <generator> element within the id element is used to generate the
primary key values automatically. The class attribute of the generator
element is set to native
6. The <property> element is used to map a Java class property to a
column in the database table. The name attribute of the element
refers to the property in the class and the column attribute refers to
the column in the database table. The type attribute holds the
hibernate mapping type, this mapping types will convert from Java
to SQL data type.
Hibernate Query Language(HQL)
Hibernate Query Language (HQL) is same as SQL
(Structured Query Language) but it doesn't depends on the
table of the database.
Instead of table name, we use class name in HQL. So it is
database independent query language.
Keywords like SELECT, FROM, and WHERE, etc., are not
case sensitive, but properties like table and column names are
case sensitive in HQL.
Advantage of HQL
There are many advantages of HQL. They are as follows:
database independent
supports polymorphic queries
easy to learn for Java Programmer
Example of HQL to get all the records
Query query=session.createQuery("from Emp");//here persistent class nam
e is Emp
List list=query.list();
Example of HQL to get records with pagination
Query query=session.createQuery("from Emp");
query.setFirstResult(5);
query.setMaxResult(10);
List list=query.list();//will return the records from 5 to 10th number
Example of HQL delete query
Query query=session.createQuery("delete from Emp where id=100");
//specifying class name (Emp) not tablename
query.executeUpdate();
Hibernate - O/R Mappings
So far, we have seen very basic O/R mapping using hibernate,
but there are three most important mapping topics, which we
have to learn in detail.
These are −
Mapping of collections and
Mapping of associations between entity classes
Association Mappings
The mapping of associations between entity classes and the
relationships between tables is the soul of ORM.
 Following are the four ways in which the cardinality of the
relationship between the objects can be expressed.
 An association mapping can be unidirectional as well as
bidirectional.
Hibernate - Many-to-One Mappings
A many-to-one association is the most common kind of
association where an Object can be associated with multiple
objects. For example, the same address object can be associated
with multiple employee objects.
Define Hibernate Mapping File
The <many-to-one> element will be used to define the rule to
establish a many-to-one relationship between EMPLOYEE and
ADDRESS entities.
<?xml version = "1.0" encoding = "utf-8"?>---
<hibernate-mapping>
<class name = "Employee" table = "EMPLOYEE">
<meta attribute = "class-description">
This class contains the employee detail. </meta>
<id name = "id" type = "int" column = "id">
<generator class="native"/>
</id> <property name = "firstName" column = "first_name" type = "string"/>
<property name = "lastName" column = "last_name" type = "string"/>
<property name = "salary" column = "salary" type = "int"/>
<many-to-one name = "address" column = "address" class="Address" not-null="true"/>
</class>
<class name = "Address" table="ADDRESS">
<meta attribute = "class-description"> This class contains the address detail.
</meta>
<id name = "id" type = "int" column = "id">
<generator class="native"/> </id>
<property name = "street" column = "street_name" type = "string"/>
</class>
</hibernate-mapping>
The <many-to-one>element is used to set the relationship
between EMPLOYEE and ADDRESS entities.
The name attribute is set to the defined variable in the parent
class, in our case it is address.
The column attribute is used to set the column name in the
parent table EMPLOYEE.
Hibernate - One-to-Many Mappings
A one-to-one association is similar to many-to-one association with a
difference that the column will be set as unique. For example, an address
object can be associated with a single employee object.
Let’s look at the following entity relationship
diagram to see one-to-many association:
For this example, we will implement a Cart system, where we have a table for
Cart and another table for Items.
A Cart can have multiple items, so here we have a one-to-many mapping with
cart_id as a primary key in the Cart table and this association is constrained
by the foreign key in the Items table.
Hibernate - One-to-One Mappings
First of all we would need to setup One to One mapping in database tables.
We will create two tables for our example – Transaction and Customer.
Both of these tables will have one to one mapping.
Transaction will be the primary table and we will be using Foreign Key in
Customer table for one-to-one mapping.
Transaction Customer
Hibernate - Many-to-Many Mappings
Many-to-Many mapping is usually implemented in database using a Join Table.
For example we can have Cart and Item table and Cart_Items table for many-to-many mapping.
Every cart can have multiple items
and every item can be part of multiple carts, so we have a many to many mapping here.

More Related Content

PDF
Hibernate Presentation
guest11106b
 
PPS
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
PDF
JPA and Hibernate
elliando dias
 
PPT
Java Persistence API (JPA) Step By Step
Guo Albert
 
PDF
Spring Data JPA
Knoldus Inc.
 
PPSX
Java annotations
FAROOK Samath
 
PPTX
Java Spring Framework
Mehul Jariwala
 
PPT
Spring ppt
Mumbai Academisc
 
Hibernate Presentation
guest11106b
 
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
JPA and Hibernate
elliando dias
 
Java Persistence API (JPA) Step By Step
Guo Albert
 
Spring Data JPA
Knoldus Inc.
 
Java annotations
FAROOK Samath
 
Java Spring Framework
Mehul Jariwala
 
Spring ppt
Mumbai Academisc
 

What's hot (20)

PPT
Jsp ppt
Vikas Jagtap
 
PPT
JDBC – Java Database Connectivity
Information Technology
 
PDF
Java I/O
Jussi Pohjolainen
 
PDF
Spring Boot
HongSeong Jeon
 
PPTX
Introduction to Spring Framework
Serhat Can
 
PPTX
Spring boot
Pradeep Shanmugam
 
PPTX
Introduction to Spring Boot
Purbarun Chakrabarti
 
PPSX
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
PDF
Spring Framework - AOP
Dzmitry Naskou
 
PDF
Java 8 Lambda Expressions
Scott Leberknight
 
PDF
jQuery for beginners
Arulmurugan Rajaraman
 
PPTX
Angularjs PPT
Amit Baghel
 
PPTX
Event In JavaScript
ShahDhruv21
 
PPT
Java EE Introduction
ejlp12
 
PPT
Java Servlets
BG Java EE Course
 
PPT
Hibernate
Ajay K
 
PPT
Spring Core
Pushan Bhattacharya
 
PPT
Hibernate architecture
Anurag
 
PDF
Basics of JavaScript
Bala Narayanan
 
Jsp ppt
Vikas Jagtap
 
JDBC – Java Database Connectivity
Information Technology
 
Spring Boot
HongSeong Jeon
 
Introduction to Spring Framework
Serhat Can
 
Spring boot
Pradeep Shanmugam
 
Introduction to Spring Boot
Purbarun Chakrabarti
 
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
Spring Framework - AOP
Dzmitry Naskou
 
Java 8 Lambda Expressions
Scott Leberknight
 
jQuery for beginners
Arulmurugan Rajaraman
 
Angularjs PPT
Amit Baghel
 
Event In JavaScript
ShahDhruv21
 
Java EE Introduction
ejlp12
 
Java Servlets
BG Java EE Course
 
Hibernate
Ajay K
 
Spring Core
Pushan Bhattacharya
 
Hibernate architecture
Anurag
 
Basics of JavaScript
Bala Narayanan
 
Ad

Similar to Hibernate ppt (20)

PPT
Basic Hibernate Final
Rafael Coutinho
 
PPTX
Module-3 for career and JFSD ppt for study.pptx
ViratKohli78
 
PPTX
Hibernate tutorial
Mumbai Academisc
 
PPT
Hibernate
Shaharyar khan
 
PPTX
Hibernate example1
myrajendra
 
PPTX
Hibernate
Prashant Kalkar
 
PPT
Hibernate Tutorial
Ram132
 
PPTX
Session 39 - Hibernate - Part 1
PawanMM
 
PDF
Hibernate 3
Rajiv Gupta
 
PPTX
Hibernate in Nutshell
Onkar Deshpande
 
PPT
Patni Hibernate
patinijava
 
PPT
Hibernate
Murali Pachiyappan
 
ODP
Hibernate 18052012
Manisha Balwadkar
 
PPTX
Hibernate
Mallikarjuna G D
 
PPTX
Session 40 - Hibernate - Part 2
PawanMM
 
PPT
Hibernate for Beginners
Ramesh Kumar
 
PPTX
Hibernate Training Session1
Asad Khan
 
PDF
Hibernate presentation
Luis Goldster
 
PPSX
Hibernate - Part 2
Hitesh-Java
 
PDF
inf5750---lecture-2.-c---hibernate-intro.pdf
bhqckkgwglxjcuctdf
 
Basic Hibernate Final
Rafael Coutinho
 
Module-3 for career and JFSD ppt for study.pptx
ViratKohli78
 
Hibernate tutorial
Mumbai Academisc
 
Hibernate
Shaharyar khan
 
Hibernate example1
myrajendra
 
Hibernate
Prashant Kalkar
 
Hibernate Tutorial
Ram132
 
Session 39 - Hibernate - Part 1
PawanMM
 
Hibernate 3
Rajiv Gupta
 
Hibernate in Nutshell
Onkar Deshpande
 
Patni Hibernate
patinijava
 
Hibernate 18052012
Manisha Balwadkar
 
Hibernate
Mallikarjuna G D
 
Session 40 - Hibernate - Part 2
PawanMM
 
Hibernate for Beginners
Ramesh Kumar
 
Hibernate Training Session1
Asad Khan
 
Hibernate presentation
Luis Goldster
 
Hibernate - Part 2
Hitesh-Java
 
inf5750---lecture-2.-c---hibernate-intro.pdf
bhqckkgwglxjcuctdf
 
Ad

Recently uploaded (20)

PDF
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
Marta Fijak
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTX
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
PPTX
Understanding operators in c language.pptx
auteharshil95
 
PPTX
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PPTX
How to Manage Global Discount in Odoo 18 POS
Celine George
 
PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
mansk2
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PDF
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
PDF
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
PDF
Introducing Procurement and Supply L2M1.pdf
labyankof
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PPTX
Presentation on Janskhiya sthirata kosh.
Ms Usha Vadhel
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
The Final Stretch: How to Release a Game and Not Die in the Process.
Marta Fijak
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
Understanding operators in c language.pptx
auteharshil95
 
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
How to Manage Global Discount in Odoo 18 POS
Celine George
 
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
Week 4 Term 3 Study Techniques revisited.pptx
mansk2
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
Introducing Procurement and Supply L2M1.pdf
labyankof
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
Presentation on Janskhiya sthirata kosh.
Ms Usha Vadhel
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 

Hibernate ppt

  • 2. Introduction to Hibernate. Hibernate was started in 2001 by Gavin King as an alternative to EJB2 Hibernate simplifies the development of java application. C,C++,Java,etc.. Are programming languages. JDBC,SERVLET,JSP,etc…are technologies. Hibernate,Spring,etc..are framework.
  • 3. ORM-Object Relational Mapping ORM is a programming technique which is used to convert object into a relational database. Java Objects Directly Mapping Relational DB Object Mapping Relational
  • 4. Continues…. ORM framework is Hibernate. Hibernate is an ORM tool which means it is used to map plain java objects to tables of a relational database and vice-versa. Your Application ORM-Middleware acting as a bridge between application and DB DB
  • 5. The “CRUD” Operations handover the object to Hibernate. Hibernate use JDBC internally to talk to the relational database for persisting. For ex: Student Class Name RollNo Address Mobile
  • 6. Table name:Student_Info Name RollNo Address Mobile Student student=new student(“Anu”,”1”,”ABCD”,”9852xxxx”);
  • 7. In the above example if we are using JDBC,the programmer need to write a lengthy code. Instead, if we are using Hibernate, programmer want just to pass the java object which you want to store and persist implicitly and will generate optimized query and are stored data into table. If we are using hibernate the code will be like this:
  • 8. public void insert Student_Info(Student student) { Session session=factory.openSession(); Transaction tx=null; try{ tx=session.beginTransaction(); Session.save(student); tx.commit();} Catch(Hibernate Exception e){if(tx!=null)tx.rollback(); e.PrintStackTrace(); }Finally {session.close();}}
  • 9. In JDBC retrieval of data is performed by using result set.It will be little bit difficult for the programmer to write the code. In Hibernate,the code will be like this: List Student_InfoList=Session.createQuery(“FROM Student_Info”).list();
  • 10. Advantages of using Hibernate: Faster retrieval of data. • Can retrieve data only in a single line of code in hibernate. Opening and closing of DB connection would no longer be a problem. • Some times the programmer forget to close the connection, they will lead to memory leak problems. But Hibernate will do it implicitly. Do not bother about change in a column of a table need only to change in one place in XML file or java annotation in java model object. • Changing Mobile to Phone No:
  • 11. Hibernate Architecture Hibernate is a ORM framework that is built on the top of multiple technologies like JDBC,JNDI(Java Naming Directory Interface),JTA(Java Transaction API) etc…to develop object based ORM mapping persistence logic as a db software independent persistence logic. Hibernate is a framework, it does not interact directly with db.
  • 12. •JAVA uses i/p in the form of objects. •Hibernate give o/p to application in the form of objects. •Hibernate take support of one or more technologies to interact with db through JDBC driver. •Once persistence operations is done in db s/w results goes to hibernate framework through JDBC driver and JTA.
  • 14. Following section gives brief description of each of the class objects involved in Hibernate Application Architecture. Configuration Object •The Configuration object is the first Hibernate object you create in any Hibernate application. •It is usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate.
  • 15. The Configuration object provides two keys components − Database Connection − This is handled through one or more configuration files supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml. Class Mapping Setup − This component creates the connection between the Java classes and database tables.
  • 16. Class objects in hibernate Continues…. SessionFactory Object • The SessionFactory is a heavyweight object; it is usually created during application start up and kept for later use. • You would need one SessionFactory object per database using a separate configuration file. So, if you are using multiple databases, then you would have to create multiple SessionFactory objects.
  • 17. Class objects in hibernate Continues…. Session Object •The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. •The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed.
  • 18. Class objects in hibernate Continues…. Transaction Object •This is an optional object and Hibernate applications may choose not to use this interface •Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA).
  • 19. Class objects in hibernate Continues…. Query Object •Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects.
  • 20. Class objects in hibernate Continues…. Criteria Object •Criteria objects are used to create and execute object oriented criteria queries to retrieve objects.
  • 21. Hibernate - Mapping Files An Object/relational mappings are usually defined in an XML document. This mapping file instructs Hibernate — how to map the defined class or classes to the database tables? Consider an ex: create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) );
  • 22. Based on the two above entities, we can define following mapping file, which instructs Hibernate how to map the defined class or classes to the database tables. <?xml version = "1.0" encoding = "utf-8"?>--- <hibernate-mapping> <class name = "Employee" table = "EMPLOYEE"> <meta attribute = "class-description"> This class contains the employee detail. </meta> <id name = "id" type = "int" column = "id"> <generator class="native"/> </id> <property name = "firstName" column = "first_name" type = "string"/> <property name = "lastName" column = "last_name" type = "string"/> <property name = "salary" column = "salary" type = "int"/> </class> </hibernate-mapping>
  • 23. You should save the mapping document in a file with the format <classname>.hbm.xml. Here,We saved our mapping document in the file Employee.hbm.xml. Let us see understand a little detail about the mapping elements used in the mapping file − 1. The mapping document is an XML document having <hibernate- mapping> as the root element, which contains all the <class> elements.
  • 24. 2.The <class> elements are used to define specific mappings from a Java classes to the database tables. 3. The <meta> element is optional element and can be used to create the class description. 4. The <id> element maps the unique ID attribute in class to the primary key of the database table. 5. The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to native
  • 25. 6. The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.
  • 26. Hibernate Query Language(HQL) Hibernate Query Language (HQL) is same as SQL (Structured Query Language) but it doesn't depends on the table of the database. Instead of table name, we use class name in HQL. So it is database independent query language. Keywords like SELECT, FROM, and WHERE, etc., are not case sensitive, but properties like table and column names are case sensitive in HQL.
  • 27. Advantage of HQL There are many advantages of HQL. They are as follows: database independent supports polymorphic queries easy to learn for Java Programmer
  • 28. Example of HQL to get all the records Query query=session.createQuery("from Emp");//here persistent class nam e is Emp List list=query.list(); Example of HQL to get records with pagination Query query=session.createQuery("from Emp"); query.setFirstResult(5); query.setMaxResult(10); List list=query.list();//will return the records from 5 to 10th number
  • 29. Example of HQL delete query Query query=session.createQuery("delete from Emp where id=100"); //specifying class name (Emp) not tablename query.executeUpdate();
  • 30. Hibernate - O/R Mappings So far, we have seen very basic O/R mapping using hibernate, but there are three most important mapping topics, which we have to learn in detail. These are − Mapping of collections and Mapping of associations between entity classes
  • 31. Association Mappings The mapping of associations between entity classes and the relationships between tables is the soul of ORM.  Following are the four ways in which the cardinality of the relationship between the objects can be expressed.  An association mapping can be unidirectional as well as bidirectional.
  • 32. Hibernate - Many-to-One Mappings A many-to-one association is the most common kind of association where an Object can be associated with multiple objects. For example, the same address object can be associated with multiple employee objects. Define Hibernate Mapping File The <many-to-one> element will be used to define the rule to establish a many-to-one relationship between EMPLOYEE and ADDRESS entities.
  • 33. <?xml version = "1.0" encoding = "utf-8"?>--- <hibernate-mapping> <class name = "Employee" table = "EMPLOYEE"> <meta attribute = "class-description"> This class contains the employee detail. </meta> <id name = "id" type = "int" column = "id"> <generator class="native"/> </id> <property name = "firstName" column = "first_name" type = "string"/> <property name = "lastName" column = "last_name" type = "string"/> <property name = "salary" column = "salary" type = "int"/> <many-to-one name = "address" column = "address" class="Address" not-null="true"/> </class> <class name = "Address" table="ADDRESS"> <meta attribute = "class-description"> This class contains the address detail. </meta> <id name = "id" type = "int" column = "id"> <generator class="native"/> </id> <property name = "street" column = "street_name" type = "string"/> </class> </hibernate-mapping>
  • 34. The <many-to-one>element is used to set the relationship between EMPLOYEE and ADDRESS entities. The name attribute is set to the defined variable in the parent class, in our case it is address. The column attribute is used to set the column name in the parent table EMPLOYEE.
  • 35. Hibernate - One-to-Many Mappings A one-to-one association is similar to many-to-one association with a difference that the column will be set as unique. For example, an address object can be associated with a single employee object.
  • 36. Let’s look at the following entity relationship diagram to see one-to-many association:
  • 37. For this example, we will implement a Cart system, where we have a table for Cart and another table for Items. A Cart can have multiple items, so here we have a one-to-many mapping with cart_id as a primary key in the Cart table and this association is constrained by the foreign key in the Items table.
  • 38. Hibernate - One-to-One Mappings First of all we would need to setup One to One mapping in database tables. We will create two tables for our example – Transaction and Customer. Both of these tables will have one to one mapping. Transaction will be the primary table and we will be using Foreign Key in Customer table for one-to-one mapping. Transaction Customer
  • 39. Hibernate - Many-to-Many Mappings Many-to-Many mapping is usually implemented in database using a Join Table. For example we can have Cart and Item table and Cart_Items table for many-to-many mapping. Every cart can have multiple items and every item can be part of multiple carts, so we have a many to many mapping here.