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

Java rmi
Java rmiJava rmi
Java rmi
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Enterprise JavaBeans(EJB)
Enterprise JavaBeans(EJB)Enterprise JavaBeans(EJB)
Enterprise JavaBeans(EJB)
 
Spring & hibernate
Spring & hibernateSpring & hibernate
Spring & hibernate
 
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...
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
 
Getting started with entity framework
Getting started with entity framework Getting started with entity framework
Getting started with entity framework
 
Tomcat
TomcatTomcat
Tomcat
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Spring boot
Spring bootSpring boot
Spring boot
 
enterprise java bean
enterprise java beanenterprise java bean
enterprise java bean
 
JavaFX Presentation
JavaFX PresentationJavaFX Presentation
JavaFX Presentation
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 

Similar to Hibernate ppt

Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggetsVirtual Nuggets
 
Hibernate Training Session1
Hibernate Training Session1Hibernate Training Session1
Hibernate Training Session1Asad Khan
 
Patni Hibernate
Patni   HibernatePatni   Hibernate
Patni Hibernatepatinijava
 
java framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptxjava framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptxramanujsaini2001
 
Java hibernate orm implementation tool
Java hibernate   orm implementation toolJava hibernate   orm implementation tool
Java hibernate orm implementation tooljavaease
 
Hibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ NizampetHibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ NizampetJayarajus
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An IntroductionNguyen Cao
 
Learn HIBERNATE at ASIT
Learn HIBERNATE at ASITLearn HIBERNATE at ASIT
Learn HIBERNATE at ASITASIT
 
Hibernate Session 1
Hibernate Session 1Hibernate Session 1
Hibernate Session 1b_kathir
 

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 in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
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
 
java framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptxjava framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptx
 
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
 

Recently uploaded

NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 

Recently uploaded (20)

NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.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.