SlideShare a Scribd company logo
1 of 39
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.
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

What's hot

Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)Manisha Keim
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Edureka!
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesecosio GmbH
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot IntroductionJeevesh Pandey
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NETRajkumarsoy
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 

What's hot (20)

Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Linq
LinqLinq
Linq
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
LINQ in C#
LINQ in C#LINQ in C#
LINQ in C#
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 

Similar to Hibernate ppt

Similar to Hibernate ppt (20)

Hibernate
HibernateHibernate
Hibernate
 
Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggets
 
Hibernate 3
Hibernate 3Hibernate 3
Hibernate 3
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
Hibernate Training Session1
Hibernate Training Session1Hibernate Training Session1
Hibernate Training Session1
 
Patni Hibernate
Patni   HibernatePatni   Hibernate
Patni Hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
Introduction to odbms
Introduction to odbmsIntroduction to odbms
Introduction to odbms
 
Java hibernate orm implementation tool
Java hibernate   orm implementation toolJava hibernate   orm implementation tool
Java hibernate orm implementation tool
 
Hibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ NizampetHibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ Nizampet
 
Hibernate.pdf
Hibernate.pdfHibernate.pdf
Hibernate.pdf
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An Introduction
 
Introduction to Hibernate
Introduction to HibernateIntroduction to Hibernate
Introduction to Hibernate
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
Learn HIBERNATE at ASIT
Learn HIBERNATE at ASITLearn HIBERNATE at ASIT
Learn HIBERNATE at ASIT
 
Hibernate Session 1
Hibernate Session 1Hibernate Session 1
Hibernate Session 1
 
Hibernate
HibernateHibernate
Hibernate
 
NHibernate
NHibernateNHibernate
NHibernate
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 

Recently uploaded

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 

Recently uploaded (20)

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 

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.
  • 13.
  • 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.