SlideShare une entreprise Scribd logo
1  sur  47
Hibernate Kick off
1.
2.
3.
4.
5.
6.
7.

Hibernate Introduction
Why to use Hibernate
Steps to use/configure hibernate in an application
simple case study
Transaction in Hibernate
Using Criteria in Hibernate
Caching in Hibernate
Hibernate Introduction:
Hibernate is a powerful, high performance object/relational persistence and
query service. Hibernate lets you develop persistent classes following objectoriented idiom - including association, inheritance, polymorphism, composition,
and collections. Hibernate allows you to express queries in its own portable
SQL extension (HQL), as well as in native SQL, or with an object-oriented
Criteria and Example API.
 
 Object/Relational Mapping Hibernate Dual-Layer Cache Architecture
 Highly scalable architecture
 J2EE integration
 Object Relational tool ( JDO, Hibernate, and iBatis SQL Maps, TopLink)
 
Hibernate supports these following databases:
Why to use Hibernate
In traditional approach:
o Too many SQL statements
o Manually handled associations
o Database dependent
Hibernate architecture
Steps to use/configure hibernate in an application:

A. Installing the Hibernate core and support JAR libraries into your project
B.

Creating a Hibernate.cfg.xml file to describe how to access your database

C.

Selecting appropriate SQL Dialect for the database.

D.

Creating individual mapping descriptor files for each persistable Java
classes
Steps to use Hibernate

A. Install the Hibernate core and JAR libraries
Steps to use Hibernate

B. Creating a Hibernate.cfg.xml :
Before Hibernate can retrieve and persist objects for us, we need to tell it the
settings about our application. For example,





which kind of objects are persistent objects?
Which kind of database are we using?
How to connect to the database?
What is the size of Connection pool?

There are three ways to configure Hibernate in total:
1.      XML configuration
2.       programmatic configuration
3.       properties file configuration.
9. Steps to use Hibernate

XML Configuration
Steps to use Hibernate

C.
Selecting appropriate SQL Dialect for the
database.
The dialect property determines the dialect to be used when generating
queries. Hibernate supports dialects for all popular Relational Database
Management Systems (RDBMS), such as DB2 or Oracle™. Therefore, for
example, if you use Oracle during development and want to move to DB2 in
production, changes will only be required in the hibernate.cfg.xml file.
Steps to use Hibernate

A.    Creating individual mapping/descriptor files for
each persistable Java classes/Table in DB

Table

JAVA
POJO Class

XML

HBM File

RDBMS

A
12. Steps to use Hibernate

A Table in Database

 
 
 

CREATE TABLE BOOK (
 
 ISBN   VARCHAR(50) NOT NULL,
 
 NAME VARCHAR(100) NOT NULL,
 
 PRICE INT  NOT NULL,
 
PRIMARY KEY (ISBN)
 
);
Steps to use Hibernate

Java (POJO):
Steps to use Hibernate

Hibernate-mapping: (*.hbm.xml)

0
4

simple case study
simple case study
Creating global session factory:
For an application using Hibernate as O/R mapping framework, a global
session factory should be created and accessed through a particular interface.
Here we use a static variable for storing the session factory. It is initialized in a
static block when this class is loaded for the first time.
Simple Case Study

Using the SessionFactory in Application:
 
SessionFactory factory = HibernateUtil.getSessionFactory();
 
Session session = factory.openSession();  
try {

} finally {

//…………………..
// Using the session to retrieve objects
//……………………………….
session.close();

}
SessionFactorys are immutable. The behaviour of a SessionFactory is
controlled by properties supplied at configuration time.
Simple Case Study

Retrieving objects
 

Book book = (Book)
session.load(Book.class, isbn);
or
Book book = (Book) session.get(Book.class,
isbn);
 

What’s the difference between load() and get() ?
The first difference is that when the given ID could not be found, load() will
throw an exception “org.hibernate.ObjectNotFoundException”, while get() will
return a null object.
The second difference is that load() just returns a proxy by default and
database won’t be hit until the proxy is first invoked. The get() will hit the
database immediately.
19. Simple Case Study

Using HQL (Hibernate Query Language):

If you are sure that there will be only one object matching, you can use the
uniqueResult() method to retrieve the unique result object.

So, the code would appear as:
20. Simple Case Study

persisting Objects:
 
For saving a newly created object, we can use the save() method. Hibernate
will issue an INSERT statement.
 
session.save(book);
 
For updating an existing object, we can use the update() method. Hibernate will
issue an UPDATE statement.
 
session.update(book);
 
For deleting an existing object, we can use the delete() method. Hibernate will
issue a DELETE statement.
 
session.delete(book);
Id Generation in Hibernate
Simple Case Study

ID generation in Hibernate

 
There are three approaches to set ID:

 

a. Sequence
b. Identity
c.

Native
23. Simple Case Study

ID generation in Hibernate

 
There are three approaches to set ID:

 
a.Sequence

To generate an ID is to use an auto-incremented sequence number. For some
kinds of databases (including HSQLDB), we can use a sequence/generator to
generate this sequence number:
Simple Case Study

b. Identity:
To generate an auto-incremented sequence
number is to use an identity column of a table.
25. Simple Case Study

c. Native:
most suitable strategy to use for your database
26. Simple Case Study

primary key generation using multiple columns:
Table:
27. Simple Case Study

Java (POJO Class)
28. Simple Case Study

Mapping (an HBM file)
5. Transaction in Hibernate:
Transaction in Hibernate:
31. Transaction in Hibernate

Example : select
32. Transaction in Hibernate

Example : update
Transaction in Hibernate

Example : delete
6 Using Criteria in Hibernate
35. Transaction in Hibernate

Sometimes we need to build up a query dynamically in our application,
e.g. for an advanced search function.“Criteria Queries” is an alternative
way of HQL query.The traditional method of doing this is to generate a HQL
statement, or SQL statement if not using Hibernate, by string
concatenation. The problem for this method is making your code hard to
maintain because of the hard reading statement fragments.

Traditinal approach:
if (startDate != null) {
if (firstClause) {
query = query + " where ";
} else {
query = query + " and ";
query += " s.date >= '" + startDate + "'";
}
// And so on...
Transaction in Hibernate

Hibernate Criteria:
Criteria criteria = session.createCriteria(Book.class);
if (startDate != null) {
criteria.add(Expression.ge("date",startDate);
}
if (endDate != null) {
criteria.add(Expression.le("date",endDate);
}
List results = criteria.list();
37. Transaction in Hibernate

SELECT * FROM ORDERS WHERE ORDER_ID=’1092’;
In Cretira it would become:
List orders= session.createCriteria(Order.class)
.add(Restrictions.eq(“orderId”,”1092”))
.list();
SELECT O.*, P.* FROM ORDERS O, PRODUCT P WHERE
O.ORDER_ID=P.ORDER_ID AND P.ID=’1111’;
Would become
List orders = session.createCriteria(Order.class)
.setFetchMode(“products”,FetchMode.JOIN)
.add(Restrictions.eq(“id”,”1111”))
.list();
38. Transaction in Hibernate

This criteria query corresponds to the following HQL query:

from Book book
where book.name = 'Hibernate for Beginners'
39. Transaction in Hibernate

•Restriction.between is used to apply a "between" constraint to the field.
•Restriction.eq is used to apply an "equal" constraint to the field.
•Restriction.ge is used to apply a "greater than or equal" constraint to the field.
•Restriction.gt is used to apply a "greater than" constraint to the field.
•Restriction.idEq is used to apply an "equal" constraint to the identifier
property.
•Restriction.in is used to apply an "in" constraint to the field.
•Restriction.isNotNull is used to apply an "is not null" constraint to the field.
•Restriction.isNull is used to apply an "is null" constraint to the field.
•Restriction.ne is used to apply a "not equal" constraint to the field.
IN:
criteria.add(Restrictions.in("newCourseID", courseIDs));
 

7. Caching in Hibernate:
41. Caching in Hibernate

Hibernate supports the caching of persistent
objects at different levels:
1 st level of caching
2 nd Level of caching
42. Caching in Hibernate

1. 1st level of caching:
 
Suppose we get an object with same identifier
for two times within a session, will Hibernate
query the database for two times? 
43. Caching in Hibernate

If we inspect the SQL statements executed by
Hibernate, we will find that only one database
query is made. That means Hibernate is caching
our objects in the same session. This kind of
caching is called “first level caching”, whose
caching scope is a session.
 
But how about getting an object with same
identifier for two times in two different sessions?
44. Caching in Hibernate

2 nd Level of caching:
45. Caching in Hibernate

 We will find that two database queries are made.
That means Hibernate is not caching the
persistent objects across different sessions by
default.
We need to turn on this “second level caching”
whose caching scope is a session factory.
46 Caching in Hibernate

To enable 2nd level of caching, update the ‘hibernate.cfg.xml’

To monitor the caching activities of Hibernate at runtime, we can add the
following line to the log4j configuration file “log4j.properties”.
log4j.logger.org.hibernate.cache=debug
Thank you.

Contenu connexe

Tendances

Introduction To Hibernate
Introduction To HibernateIntroduction To Hibernate
Introduction To Hibernateashishkulkarni
 
Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsRichie Rump
 
NoSQL Endgame Percona Live Online 2020
NoSQL Endgame Percona Live Online 2020NoSQL Endgame Percona Live Online 2020
NoSQL Endgame Percona Live Online 2020Thodoris Bais
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code FirstJames Johnson
 
Hibernate
Hibernate Hibernate
Hibernate Sunil OS
 
Hibernate Session 1
Hibernate Session 1Hibernate Session 1
Hibernate Session 1b_kathir
 
Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)Igor Anishchenko
 
Reusing existing data_layer_to_persist_multi_f
Reusing existing data_layer_to_persist_multi_fReusing existing data_layer_to_persist_multi_f
Reusing existing data_layer_to_persist_multi_fbol.com
 
JPA Code Generation via MyEclipse
JPA Code Generation via MyEclipseJPA Code Generation via MyEclipse
JPA Code Generation via MyEclipseGuo Albert
 
Electron, databases, and RxDB
Electron, databases, and RxDBElectron, databases, and RxDB
Electron, databases, and RxDBBen Gotow
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOSMake School
 
Storlets fb session_16_9
Storlets fb session_16_9Storlets fb session_16_9
Storlets fb session_16_9Eran Rom
 
From Java Code to Java Heap: Understanding the Memory Usage of Your App - Ch...
From Java Code to Java Heap: Understanding the Memory Usage of Your App  - Ch...From Java Code to Java Heap: Understanding the Memory Usage of Your App  - Ch...
From Java Code to Java Heap: Understanding the Memory Usage of Your App - Ch...jaxLondonConference
 

Tendances (20)

Introduction To Hibernate
Introduction To HibernateIntroduction To Hibernate
Introduction To Hibernate
 
Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic Unicorns
 
NoSQL Endgame Percona Live Online 2020
NoSQL Endgame Percona Live Online 2020NoSQL Endgame Percona Live Online 2020
NoSQL Endgame Percona Live Online 2020
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
 
Hibernate
Hibernate Hibernate
Hibernate
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 
Hibernate Session 1
Hibernate Session 1Hibernate Session 1
Hibernate Session 1
 
Core Data
Core DataCore Data
Core Data
 
Requery overview
Requery overviewRequery overview
Requery overview
 
Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)
 
Digital Object Identifiers for EOSDIS data
Digital Object Identifiers for EOSDIS dataDigital Object Identifiers for EOSDIS data
Digital Object Identifiers for EOSDIS data
 
Reusing existing data_layer_to_persist_multi_f
Reusing existing data_layer_to_persist_multi_fReusing existing data_layer_to_persist_multi_f
Reusing existing data_layer_to_persist_multi_f
 
Lokijs
LokijsLokijs
Lokijs
 
JPA Code Generation via MyEclipse
JPA Code Generation via MyEclipseJPA Code Generation via MyEclipse
JPA Code Generation via MyEclipse
 
Electron, databases, and RxDB
Electron, databases, and RxDBElectron, databases, and RxDB
Electron, databases, and RxDB
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOS
 
Storlets fb session_16_9
Storlets fb session_16_9Storlets fb session_16_9
Storlets fb session_16_9
 
From Java Code to Java Heap: Understanding the Memory Usage of Your App - Ch...
From Java Code to Java Heap: Understanding the Memory Usage of Your App  - Ch...From Java Code to Java Heap: Understanding the Memory Usage of Your App  - Ch...
From Java Code to Java Heap: Understanding the Memory Usage of Your App - Ch...
 
[iOS] Data Storage
[iOS] Data Storage[iOS] Data Storage
[iOS] Data Storage
 

Similaire à Hibernate for Beginners

Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate NotesKaniska Mandal
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questionsDhiraj Champawat
 
Hibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaHibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaEdureka!
 
Hibernate in XPages
Hibernate in XPagesHibernate in XPages
Hibernate in XPagesToby Samples
 
Hibernate - Part 2
Hibernate - Part 2 Hibernate - Part 2
Hibernate - Part 2 Hitesh-Java
 
Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2PawanMM
 
Hibernate Interview Questions and Answers
Hibernate Interview Questions and AnswersHibernate Interview Questions and Answers
Hibernate Interview Questions and AnswersAnuragMourya8
 
Hibernate
HibernateHibernate
HibernateAjay K
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentationManav Prasad
 
nHibernate Query
nHibernate QuerynHibernate Query
nHibernate QueryGuo Albert
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Trainingsourabh aggarwal
 
Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1PawanMM
 
Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggetsVirtual Nuggets
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate TutorialSyed Shahul
 
Introduction to NHibernate
Introduction to NHibernateIntroduction to NHibernate
Introduction to NHibernateDublin Alt,Net
 

Similaire à Hibernate for Beginners (20)

Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate Notes
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions
 
Hibernate Advance Interview Questions
Hibernate Advance Interview QuestionsHibernate Advance Interview Questions
Hibernate Advance Interview Questions
 
Hibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaHibernate Interview Questions | Edureka
Hibernate Interview Questions | Edureka
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
Hibernate in XPages
Hibernate in XPagesHibernate in XPages
Hibernate in XPages
 
Hibernate - Part 2
Hibernate - Part 2 Hibernate - Part 2
Hibernate - Part 2
 
Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2
 
Hibernate Interview Questions and Answers
Hibernate Interview Questions and AnswersHibernate Interview Questions and Answers
Hibernate Interview Questions and Answers
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Hibernate 18052012
Hibernate 18052012Hibernate 18052012
Hibernate 18052012
 
nHibernate Query
nHibernate QuerynHibernate Query
nHibernate Query
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Training
 
Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1
 
Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggets
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
 
Introduction to NHibernate
Introduction to NHibernateIntroduction to NHibernate
Introduction to NHibernate
 
Persistence hibernate
Persistence hibernatePersistence hibernate
Persistence hibernate
 

Dernier

Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsManeerUddin
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 

Dernier (20)

Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture hons
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 

Hibernate for Beginners

  • 2. 1. 2. 3. 4. 5. 6. 7. Hibernate Introduction Why to use Hibernate Steps to use/configure hibernate in an application simple case study Transaction in Hibernate Using Criteria in Hibernate Caching in Hibernate
  • 3. Hibernate Introduction: Hibernate is a powerful, high performance object/relational persistence and query service. Hibernate lets you develop persistent classes following objectoriented idiom - including association, inheritance, polymorphism, composition, and collections. Hibernate allows you to express queries in its own portable SQL extension (HQL), as well as in native SQL, or with an object-oriented Criteria and Example API.    Object/Relational Mapping Hibernate Dual-Layer Cache Architecture  Highly scalable architecture  J2EE integration  Object Relational tool ( JDO, Hibernate, and iBatis SQL Maps, TopLink)   Hibernate supports these following databases:
  • 4. Why to use Hibernate In traditional approach: o Too many SQL statements o Manually handled associations o Database dependent
  • 6. Steps to use/configure hibernate in an application: A. Installing the Hibernate core and support JAR libraries into your project B. Creating a Hibernate.cfg.xml file to describe how to access your database C. Selecting appropriate SQL Dialect for the database. D. Creating individual mapping descriptor files for each persistable Java classes
  • 7. Steps to use Hibernate A. Install the Hibernate core and JAR libraries
  • 8. Steps to use Hibernate B. Creating a Hibernate.cfg.xml : Before Hibernate can retrieve and persist objects for us, we need to tell it the settings about our application. For example,     which kind of objects are persistent objects? Which kind of database are we using? How to connect to the database? What is the size of Connection pool? There are three ways to configure Hibernate in total: 1.      XML configuration 2.       programmatic configuration 3.       properties file configuration.
  • 9. 9. Steps to use Hibernate XML Configuration
  • 10. Steps to use Hibernate C. Selecting appropriate SQL Dialect for the database. The dialect property determines the dialect to be used when generating queries. Hibernate supports dialects for all popular Relational Database Management Systems (RDBMS), such as DB2 or Oracle™. Therefore, for example, if you use Oracle during development and want to move to DB2 in production, changes will only be required in the hibernate.cfg.xml file.
  • 11. Steps to use Hibernate A.    Creating individual mapping/descriptor files for each persistable Java classes/Table in DB Table JAVA POJO Class XML HBM File RDBMS A
  • 12. 12. Steps to use Hibernate A Table in Database       CREATE TABLE BOOK (    ISBN   VARCHAR(50) NOT NULL,    NAME VARCHAR(100) NOT NULL,    PRICE INT  NOT NULL,   PRIMARY KEY (ISBN)   );
  • 13. Steps to use Hibernate Java (POJO):
  • 14. Steps to use Hibernate Hibernate-mapping: (*.hbm.xml) 0
  • 16. simple case study Creating global session factory: For an application using Hibernate as O/R mapping framework, a global session factory should be created and accessed through a particular interface. Here we use a static variable for storing the session factory. It is initialized in a static block when this class is loaded for the first time.
  • 17. Simple Case Study Using the SessionFactory in Application:   SessionFactory factory = HibernateUtil.getSessionFactory();   Session session = factory.openSession();   try { } finally { //………………….. // Using the session to retrieve objects //………………………………. session.close(); } SessionFactorys are immutable. The behaviour of a SessionFactory is controlled by properties supplied at configuration time.
  • 18. Simple Case Study Retrieving objects   Book book = (Book) session.load(Book.class, isbn); or Book book = (Book) session.get(Book.class, isbn);   What’s the difference between load() and get() ? The first difference is that when the given ID could not be found, load() will throw an exception “org.hibernate.ObjectNotFoundException”, while get() will return a null object. The second difference is that load() just returns a proxy by default and database won’t be hit until the proxy is first invoked. The get() will hit the database immediately.
  • 19. 19. Simple Case Study Using HQL (Hibernate Query Language): If you are sure that there will be only one object matching, you can use the uniqueResult() method to retrieve the unique result object. So, the code would appear as:
  • 20. 20. Simple Case Study persisting Objects:   For saving a newly created object, we can use the save() method. Hibernate will issue an INSERT statement.   session.save(book);   For updating an existing object, we can use the update() method. Hibernate will issue an UPDATE statement.   session.update(book);   For deleting an existing object, we can use the delete() method. Hibernate will issue a DELETE statement.   session.delete(book);
  • 21. Id Generation in Hibernate
  • 22. Simple Case Study ID generation in Hibernate   There are three approaches to set ID:   a. Sequence b. Identity c. Native
  • 23. 23. Simple Case Study ID generation in Hibernate   There are three approaches to set ID:   a.Sequence To generate an ID is to use an auto-incremented sequence number. For some kinds of databases (including HSQLDB), we can use a sequence/generator to generate this sequence number:
  • 24. Simple Case Study b. Identity: To generate an auto-incremented sequence number is to use an identity column of a table.
  • 25. 25. Simple Case Study c. Native: most suitable strategy to use for your database
  • 26. 26. Simple Case Study primary key generation using multiple columns: Table:
  • 27. 27. Simple Case Study Java (POJO Class)
  • 28. 28. Simple Case Study Mapping (an HBM file)
  • 29. 5. Transaction in Hibernate:
  • 31. 31. Transaction in Hibernate Example : select
  • 32. 32. Transaction in Hibernate Example : update
  • 34. 6 Using Criteria in Hibernate
  • 35. 35. Transaction in Hibernate Sometimes we need to build up a query dynamically in our application, e.g. for an advanced search function.“Criteria Queries” is an alternative way of HQL query.The traditional method of doing this is to generate a HQL statement, or SQL statement if not using Hibernate, by string concatenation. The problem for this method is making your code hard to maintain because of the hard reading statement fragments. Traditinal approach: if (startDate != null) { if (firstClause) { query = query + " where "; } else { query = query + " and "; query += " s.date >= '" + startDate + "'"; } // And so on...
  • 36. Transaction in Hibernate Hibernate Criteria: Criteria criteria = session.createCriteria(Book.class); if (startDate != null) { criteria.add(Expression.ge("date",startDate); } if (endDate != null) { criteria.add(Expression.le("date",endDate); } List results = criteria.list();
  • 37. 37. Transaction in Hibernate SELECT * FROM ORDERS WHERE ORDER_ID=’1092’; In Cretira it would become: List orders= session.createCriteria(Order.class) .add(Restrictions.eq(“orderId”,”1092”)) .list(); SELECT O.*, P.* FROM ORDERS O, PRODUCT P WHERE O.ORDER_ID=P.ORDER_ID AND P.ID=’1111’; Would become List orders = session.createCriteria(Order.class) .setFetchMode(“products”,FetchMode.JOIN) .add(Restrictions.eq(“id”,”1111”)) .list();
  • 38. 38. Transaction in Hibernate This criteria query corresponds to the following HQL query: from Book book where book.name = 'Hibernate for Beginners'
  • 39. 39. Transaction in Hibernate •Restriction.between is used to apply a "between" constraint to the field. •Restriction.eq is used to apply an "equal" constraint to the field. •Restriction.ge is used to apply a "greater than or equal" constraint to the field. •Restriction.gt is used to apply a "greater than" constraint to the field. •Restriction.idEq is used to apply an "equal" constraint to the identifier property. •Restriction.in is used to apply an "in" constraint to the field. •Restriction.isNotNull is used to apply an "is not null" constraint to the field. •Restriction.isNull is used to apply an "is null" constraint to the field. •Restriction.ne is used to apply a "not equal" constraint to the field. IN: criteria.add(Restrictions.in("newCourseID", courseIDs));
  • 40.   7. Caching in Hibernate:
  • 41. 41. Caching in Hibernate Hibernate supports the caching of persistent objects at different levels: 1 st level of caching 2 nd Level of caching
  • 42. 42. Caching in Hibernate 1. 1st level of caching:   Suppose we get an object with same identifier for two times within a session, will Hibernate query the database for two times? 
  • 43. 43. Caching in Hibernate If we inspect the SQL statements executed by Hibernate, we will find that only one database query is made. That means Hibernate is caching our objects in the same session. This kind of caching is called “first level caching”, whose caching scope is a session.   But how about getting an object with same identifier for two times in two different sessions?
  • 44. 44. Caching in Hibernate 2 nd Level of caching:
  • 45. 45. Caching in Hibernate  We will find that two database queries are made. That means Hibernate is not caching the persistent objects across different sessions by default. We need to turn on this “second level caching” whose caching scope is a session factory.
  • 46. 46 Caching in Hibernate To enable 2nd level of caching, update the ‘hibernate.cfg.xml’ To monitor the caching activities of Hibernate at runtime, we can add the following line to the log4j configuration file “log4j.properties”. log4j.logger.org.hibernate.cache=debug