SlideShare a Scribd company logo
1 of 29
Hibernate Association &
Collection Mapping
Also a Bit on Lazy Loading and
Fetching Strategies
Topics
• Object types in Hibernate
• Collection types in Hibernate
• Scrutinizing 1-2-Many Collections
• Fetching Strategies
2
Object Types in Hibernate
Entity Type Object
• Has its own DB
identity (i.e. PK).
• Can exist
independently of
any other entity.
• Has its own life
cycle.
Value Type Object
• Doesn’t have own DB
identity.
• Existence is dependent
on its owning entity.
• Lifespan is bounded by
the lifespan of the
owning entity.
3
Collection Types in Hibernate
Set: [java.util.HashSet]
• Unique Elements
• Unordered
List: [java.util.ArrayList]
• Duplicate Elements
• Ordered
Sorted Set:
[java.util.TreeSet]
• Unique Elements
• Ordered
Bag: [java.util.List]
• Unordered
• Duplicate Elements
Map: [java.util.Map]
• Unordered Unique Keys
• Duplicate Values
Sorted Map:
[java.util.TreeMap]
• Ordered Keys
• Duplicate Values
4
Unidirectional 1-2-Many Between Entities
class A {
int id;
String name;
List<B> bList;
...
@OneToMany
public List<B> getBList() {
return bList;
}
}
class B {
int id;
String name;
...
}
5
Unidirectional 1-2-Many Between Entities...
Resulting DB:
Conlusion:
By default Hibernate creates one-to many with join table.
This is same as:
@OneToMany
@JoinTable(name="A_B"
joinColumns=@JoinColumn(name="A_id"),
inverseJoinColumns=JoinColumn(name="bList_id")
)
6
Unidirectional 1-2-Many Between Entities...
For 1-2-Many without join table, use:
@OneToMany
@JoinColumn(name="a_id")
Resulting DB:
7
Unidirectional 1-2-Many Between Entities...
Nullable Effect in Join Column
• For the previous code, the join column is by
default nullable.
• Hence, deletion would cause Hibernate to
update row in B setting a_id = null.
• It’s the same as defining as follows:
@OneToMany
@JoinColumn(name="a_id", nullable="true")
8
Unidirectional 1-2-Many Between Entities...
Nullable Effect in Join Column (contd.)
• To set the join column NOT to be null, use:
@OneToMany
@JoinColumn(name="a_id", nullable="false")
• In that case, deletion would cause no effect in
Hibernate.
• To force delete child row when the parent is
removed, use:
@OneToMany(orphanRemoval=true)
@JoinColumn(name="a_id", nullable="false")
9
Unidirectional 1-2-Many Between Entities...
(List Semantics)
• By default, List collections are considered to be bags.
• To enforce List semantics, specify the index column:
@OneToMany
@JoinColumn(name="a_id", nullable="false")
@IndexColumn(name="idx")
A B
Id name Id a_id Name idx
1 A1 1 1 B1 0
2 1 B2 1
3 1 B3 2
10
Unidirectional 1-2-Many Between Entities...
(List Semantics)
INSERT operation
Let, a new row at idx = 1 position is to be inserted.
1. If join column is nullable, then
1 update query for deletion (i.e., set idx = null) of rows with idx ≥ 1.
2. 1 update query for updating of rows with idx ≥ 1.
3. 1 update query for insertion of new rows.
A B
Id name Id a_id Name idx
1 A1 1 1 B1 0
2 1 B2 1
3 1 B3 2
11
Unidirectional 1-2-Many Between Entities...
(List Semantics)
DELETE operation
Let, row with idx = 1 is to be deleted.
1. 1 update query for updating of rows with idx > 1.
2. If orphanRemoval = true, then
1 delete query for deleting the row with idx = 1.
Note: If join column is not nullable and orphanRemoval = false, the row
with idx = 1 will remain, hence, there will be two rows with idx = 1.
A B
Id name Id a_id Name idx
1 A1 1 1 B1 0
2 1 B2 1
3 1 B3 2
12
Unidirectional 1-2-Many Between Entities...
(List Semantics)
Lazy Loading with LazyCollectionOption.EXTRA
• Calling size() wouldn’t cause collection to
load.
• Calling get(idx) would cause only one row
with the idx value to load.
A B
Id name Id a_id Name idx
1 A1 1 1 B1 0
2 1 B2 1
3 1 B3 2
13
Unidirectional 1-2-Many Between Entities...
(Set Semantics)
Lazy Loading with LazyCollectionOption.EXTRA
• Calling size() wouldn’t cause collection to
load.
• Calling iterator.next() would cause
the entire collection to load.
A B
Id name Id a_id Name
1 A1 1 1 B1
2 1 B2
3 1 B3
14
Unidirectional 1-2-Many Between Entities...
(Set Semantics)
INSERT operation
1 update query for setting the newly added
element’s a_id.
A B
Id name Id a_id Name
1 A1 1 1 B1
2 1 B2
3 1 B3
15
Unidirectional 1-2-Many Between Entities...
(Set Semantics)
DELETE operation
If join column is nullable,
1 update query for setting a_id = null.
Else
If orphanRemoval = false
No changes would be made.
Else
Completely delete the row in B.
A B
Id name Id a_id Name
1 A1 1 1 B1
2 1 B2
3 1 B3
16
Unidirectional 1-2-Many Between Entities...
(Bag Semantics)
Similar to SET semantics...
A B
Id name Id a_id Name
1 A1 1 1 B1
2 1 B2
3 1 B3
17
Unidirectional 1-2-Many With Value Type
(Bag Semantics)
INSERT, DELETE, UPDATE operations
1. Select * from B.
2. Delete * from B where a_id = 1.
3. Insert into B all rows – along with new rows (in
case of INSERT), or except rows to be delete (in
case of DELETE).
A B
Id name a_id Name
1 A1 1 B1
1 B2
1 B3
18
Unidirectional 1-2-Many With Value Type
(Set Semantics)
INSERT operation
1. Select * from B.
2. Insert into B the new rows to be added.
A B
Id name a_id Name
1 A1 1 B1
1 B2
1 B3
19
Unidirectional 1-2-Many With Value Type
(Set Semantics)
DELETE operation
1. Select * from B.
2. Delete from B where a_id = 1 and name = ?
A B
Id name a_id Name
1 A1 1 B1
1 B2
1 B3
20
Unidirectional 1-2-Many With Value Type
(Set Semantics)
UPDATE operation
1. Select * from B.
2. Delete the row to be updated.
3. Insert the newly updated object.
A B
Id name a_id Name
1 A1 1 B1
1 B2
1 B3
21
Unidirectional 1-2-Many With Value Type
(List Semantics)
INSERT operation
1. Select * from B.
2. Update idx values in B.
3. Insert the new object.
A B
Id name a_id Name idx
1 A1 1 B1 0
1 B2 1
1 B3 2
22
Unidirectional 1-2-Many With Value Type
(List Semantics)
DELETE operation
1. Select * from B.
2. Delete from B where idx = ?
3. Update the idx of other rows.
A B
Id name a_id Name idx
1 A1 1 B1 0
1 B2 1
1 B3 2
23
Unidirectional 1-2-Many With Value Type
(List Semantics)
UPDATE operation
Doesn’t seem to work!!!
A B
Id name a_id Name idx
1 A1 1 B1 0
1 B2 1
1 B3 2
24
Unidirectional 1-2-1 Between Entities
@OneToOne
• Defaults to eager fetching.
• To force lazy loading, use:
@OneToOne(fetch=FetchType.LAZY)
A B
Id name b_id id Name
1 A1 1 1 B1
25
Fetch Modes
SELECT FETCH (Default)
• Force lazy loading.
JOIN FETCH
• If join column nullable, then outer join,
otherwise inner join.
• Force eager fetching.
BATCH-SIZE N
• Doesn’t define how many records inside in the collections are
loaded. Instead, it defines how many collections should be loaded.
• Nice for nested tree node loading.
SUBSELECT
• Not only loads this collection in the second SELECT (either lazy or
non-lazy), but also all other collections for all "owning" entities
loaded in the first SELECT.
26
Fetch Modes...
BATCH-SIZE N Example
List<A> aList = getList();
for (A a : aList) {
List<B> bList = a.getbList();
}
In Batch-size = 5, the select query would be:
select ...
from B
where a_id in (?, ?, ?, ?, ?)
A B
id name a_id Name
1 A1 1 B1
2 A2 1 B2
2 B3
27
Fetch Modes...
SUBSELECT Example
List<A> aList = getList();
for (A a : aList) {
List<B> bList = a.getbList();
}
In subselect, the select query would be:
select ...
from B
where a_id in (select id from A)
A B
id name a_id Name
1 A1 1 B1
2 A2 1 B2
2 B3
28
References
• A Short Primer On Fetching Strategies:
https://community.jboss.org/wiki/AShortPrimerO
nFetchingStrategies
• Hibernate – fetching strategies examples
http://www.mkyong.com/hibernate/hibernate-
fetching-strategies-examples/
• Bag is recommended over set:
http://stackoverflow.com/questions/1505874/hib
ernate-best-collection-type-to-use-bag-idbag-set-
list-map
29

More Related Content

What's hot

Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structurekalyanineve
 
Introduction to Data Structure : Pointer
Introduction to Data Structure : PointerIntroduction to Data Structure : Pointer
Introduction to Data Structure : PointerS P Sajjan
 
Cs301 mid-term-mega-file
Cs301 mid-term-mega-fileCs301 mid-term-mega-file
Cs301 mid-term-mega-fileWartollames
 
linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structuresDurgaDeviCbit
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Balwant Gorad
 
Ifi7184 lesson3
Ifi7184 lesson3Ifi7184 lesson3
Ifi7184 lesson3Sónia
 
Acm aleppo cpc training sixth session
Acm aleppo cpc training sixth sessionAcm aleppo cpc training sixth session
Acm aleppo cpc training sixth sessionAhmad Bashar Eter
 

What's hot (14)

Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structure
 
Unit 4 tree
Unit 4   treeUnit 4   tree
Unit 4 tree
 
Data structures using C
Data structures using CData structures using C
Data structures using C
 
Data structures
Data structuresData structures
Data structures
 
Introduction to Data Structure : Pointer
Introduction to Data Structure : PointerIntroduction to Data Structure : Pointer
Introduction to Data Structure : Pointer
 
Cs301 mid-term-mega-file
Cs301 mid-term-mega-fileCs301 mid-term-mega-file
Cs301 mid-term-mega-file
 
linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structures
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
 
Ifi7184 lesson3
Ifi7184 lesson3Ifi7184 lesson3
Ifi7184 lesson3
 
Lecture 2a arrays
Lecture 2a arraysLecture 2a arrays
Lecture 2a arrays
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Acm aleppo cpc training sixth session
Acm aleppo cpc training sixth sessionAcm aleppo cpc training sixth session
Acm aleppo cpc training sixth session
 
Arrays In C++
Arrays In C++Arrays In C++
Arrays In C++
 
Data Structures (BE)
Data Structures (BE)Data Structures (BE)
Data Structures (BE)
 

Similar to Hibernate Association & Collection Mapping Lazy Loading Fetch Strategies

Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in pythonLifna C.S
 
List - Operations and Implementation
List - Operations and ImplementationList - Operations and Implementation
List - Operations and ImplementationSagacious IT Solution
 
DATA STRUCTURES USING C -ENGGDIGEST
DATA STRUCTURES USING C -ENGGDIGESTDATA STRUCTURES USING C -ENGGDIGEST
DATA STRUCTURES USING C -ENGGDIGESTSwapnil Mishra
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3infanciaj
 
DS Module1 (1).pptx
DS Module1 (1).pptxDS Module1 (1).pptx
DS Module1 (1).pptxAnuJoseph95
 
Database index
Database indexDatabase index
Database indexRiteshkiit
 
introduction_dst.pptx
introduction_dst.pptxintroduction_dst.pptx
introduction_dst.pptxHammadTariq51
 
SORTING ALGORITHMS.DAA .Bucket, Count,Radix
SORTING ALGORITHMS.DAA .Bucket, Count,RadixSORTING ALGORITHMS.DAA .Bucket, Count,Radix
SORTING ALGORITHMS.DAA .Bucket, Count,RadixAkshiChandola
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil duttAnil Dutt
 
SQLBits X SQL Server 2012 Spatial Indexing
SQLBits X SQL Server 2012 Spatial IndexingSQLBits X SQL Server 2012 Spatial Indexing
SQLBits X SQL Server 2012 Spatial IndexingMichael Rys
 
How to choose best containers in STL (C++)
How to choose best containers in STL (C++)How to choose best containers in STL (C++)
How to choose best containers in STL (C++)Sangharsh agarwal
 
Objective The purpose of this exercise is to create a Linked List d.pdf
Objective The purpose of this exercise is to create a Linked List d.pdfObjective The purpose of this exercise is to create a Linked List d.pdf
Objective The purpose of this exercise is to create a Linked List d.pdfaliracreations
 
Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddumaneesh boddu
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structuresNiraj Agarwal
 
Please and Thank youObjective The purpose of this exercise is to .pdf
Please and Thank youObjective The purpose of this exercise is to .pdfPlease and Thank youObjective The purpose of this exercise is to .pdf
Please and Thank youObjective The purpose of this exercise is to .pdfalicesilverblr
 
Postgres can do THAT?
Postgres can do THAT?Postgres can do THAT?
Postgres can do THAT?alexbrasetvik
 

Similar to Hibernate Association & Collection Mapping Lazy Loading Fetch Strategies (20)

Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
Unit i(dsc++)
Unit i(dsc++)Unit i(dsc++)
Unit i(dsc++)
 
List - Operations and Implementation
List - Operations and ImplementationList - Operations and Implementation
List - Operations and Implementation
 
DATA STRUCTURES USING C -ENGGDIGEST
DATA STRUCTURES USING C -ENGGDIGESTDATA STRUCTURES USING C -ENGGDIGEST
DATA STRUCTURES USING C -ENGGDIGEST
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
DS Module1 (1).pptx
DS Module1 (1).pptxDS Module1 (1).pptx
DS Module1 (1).pptx
 
Database index
Database indexDatabase index
Database index
 
introduction_dst.pptx
introduction_dst.pptxintroduction_dst.pptx
introduction_dst.pptx
 
SORTING ALGORITHMS.DAA .Bucket, Count,Radix
SORTING ALGORITHMS.DAA .Bucket, Count,RadixSORTING ALGORITHMS.DAA .Bucket, Count,Radix
SORTING ALGORITHMS.DAA .Bucket, Count,Radix
 
Ch02
Ch02Ch02
Ch02
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil dutt
 
SQLBits X SQL Server 2012 Spatial Indexing
SQLBits X SQL Server 2012 Spatial IndexingSQLBits X SQL Server 2012 Spatial Indexing
SQLBits X SQL Server 2012 Spatial Indexing
 
How to choose best containers in STL (C++)
How to choose best containers in STL (C++)How to choose best containers in STL (C++)
How to choose best containers in STL (C++)
 
Objective The purpose of this exercise is to create a Linked List d.pdf
Objective The purpose of this exercise is to create a Linked List d.pdfObjective The purpose of this exercise is to create a Linked List d.pdf
Objective The purpose of this exercise is to create a Linked List d.pdf
 
Arrays in C.pptx
Arrays in C.pptxArrays in C.pptx
Arrays in C.pptx
 
Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddu
 
F sharp lists & dictionary
F sharp   lists &  dictionaryF sharp   lists &  dictionary
F sharp lists & dictionary
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structures
 
Please and Thank youObjective The purpose of this exercise is to .pdf
Please and Thank youObjective The purpose of this exercise is to .pdfPlease and Thank youObjective The purpose of this exercise is to .pdf
Please and Thank youObjective The purpose of this exercise is to .pdf
 
Postgres can do THAT?
Postgres can do THAT?Postgres can do THAT?
Postgres can do THAT?
 

More from Sharafat Ibn Mollah Mosharraf (7)

GRP GRM Development Progress Presentation
GRP GRM Development Progress PresentationGRP GRM Development Progress Presentation
GRP GRM Development Progress Presentation
 
Manners Matter: Learning Professional Etiquettes
Manners Matter: Learning Professional EtiquettesManners Matter: Learning Professional Etiquettes
Manners Matter: Learning Professional Etiquettes
 
SQL
SQLSQL
SQL
 
Effective Learning (& Teaching)
Effective Learning (& Teaching)Effective Learning (& Teaching)
Effective Learning (& Teaching)
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Android Insights - 3 [Content Providers]
Android Insights - 3 [Content Providers]Android Insights - 3 [Content Providers]
Android Insights - 3 [Content Providers]
 
Android Insights - 1 [Intents]
Android Insights - 1 [Intents]Android Insights - 1 [Intents]
Android Insights - 1 [Intents]
 

Recently uploaded

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 

Recently uploaded (20)

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 

Hibernate Association & Collection Mapping Lazy Loading Fetch Strategies

  • 1. Hibernate Association & Collection Mapping Also a Bit on Lazy Loading and Fetching Strategies
  • 2. Topics • Object types in Hibernate • Collection types in Hibernate • Scrutinizing 1-2-Many Collections • Fetching Strategies 2
  • 3. Object Types in Hibernate Entity Type Object • Has its own DB identity (i.e. PK). • Can exist independently of any other entity. • Has its own life cycle. Value Type Object • Doesn’t have own DB identity. • Existence is dependent on its owning entity. • Lifespan is bounded by the lifespan of the owning entity. 3
  • 4. Collection Types in Hibernate Set: [java.util.HashSet] • Unique Elements • Unordered List: [java.util.ArrayList] • Duplicate Elements • Ordered Sorted Set: [java.util.TreeSet] • Unique Elements • Ordered Bag: [java.util.List] • Unordered • Duplicate Elements Map: [java.util.Map] • Unordered Unique Keys • Duplicate Values Sorted Map: [java.util.TreeMap] • Ordered Keys • Duplicate Values 4
  • 5. Unidirectional 1-2-Many Between Entities class A { int id; String name; List<B> bList; ... @OneToMany public List<B> getBList() { return bList; } } class B { int id; String name; ... } 5
  • 6. Unidirectional 1-2-Many Between Entities... Resulting DB: Conlusion: By default Hibernate creates one-to many with join table. This is same as: @OneToMany @JoinTable(name="A_B" joinColumns=@JoinColumn(name="A_id"), inverseJoinColumns=JoinColumn(name="bList_id") ) 6
  • 7. Unidirectional 1-2-Many Between Entities... For 1-2-Many without join table, use: @OneToMany @JoinColumn(name="a_id") Resulting DB: 7
  • 8. Unidirectional 1-2-Many Between Entities... Nullable Effect in Join Column • For the previous code, the join column is by default nullable. • Hence, deletion would cause Hibernate to update row in B setting a_id = null. • It’s the same as defining as follows: @OneToMany @JoinColumn(name="a_id", nullable="true") 8
  • 9. Unidirectional 1-2-Many Between Entities... Nullable Effect in Join Column (contd.) • To set the join column NOT to be null, use: @OneToMany @JoinColumn(name="a_id", nullable="false") • In that case, deletion would cause no effect in Hibernate. • To force delete child row when the parent is removed, use: @OneToMany(orphanRemoval=true) @JoinColumn(name="a_id", nullable="false") 9
  • 10. Unidirectional 1-2-Many Between Entities... (List Semantics) • By default, List collections are considered to be bags. • To enforce List semantics, specify the index column: @OneToMany @JoinColumn(name="a_id", nullable="false") @IndexColumn(name="idx") A B Id name Id a_id Name idx 1 A1 1 1 B1 0 2 1 B2 1 3 1 B3 2 10
  • 11. Unidirectional 1-2-Many Between Entities... (List Semantics) INSERT operation Let, a new row at idx = 1 position is to be inserted. 1. If join column is nullable, then 1 update query for deletion (i.e., set idx = null) of rows with idx ≥ 1. 2. 1 update query for updating of rows with idx ≥ 1. 3. 1 update query for insertion of new rows. A B Id name Id a_id Name idx 1 A1 1 1 B1 0 2 1 B2 1 3 1 B3 2 11
  • 12. Unidirectional 1-2-Many Between Entities... (List Semantics) DELETE operation Let, row with idx = 1 is to be deleted. 1. 1 update query for updating of rows with idx > 1. 2. If orphanRemoval = true, then 1 delete query for deleting the row with idx = 1. Note: If join column is not nullable and orphanRemoval = false, the row with idx = 1 will remain, hence, there will be two rows with idx = 1. A B Id name Id a_id Name idx 1 A1 1 1 B1 0 2 1 B2 1 3 1 B3 2 12
  • 13. Unidirectional 1-2-Many Between Entities... (List Semantics) Lazy Loading with LazyCollectionOption.EXTRA • Calling size() wouldn’t cause collection to load. • Calling get(idx) would cause only one row with the idx value to load. A B Id name Id a_id Name idx 1 A1 1 1 B1 0 2 1 B2 1 3 1 B3 2 13
  • 14. Unidirectional 1-2-Many Between Entities... (Set Semantics) Lazy Loading with LazyCollectionOption.EXTRA • Calling size() wouldn’t cause collection to load. • Calling iterator.next() would cause the entire collection to load. A B Id name Id a_id Name 1 A1 1 1 B1 2 1 B2 3 1 B3 14
  • 15. Unidirectional 1-2-Many Between Entities... (Set Semantics) INSERT operation 1 update query for setting the newly added element’s a_id. A B Id name Id a_id Name 1 A1 1 1 B1 2 1 B2 3 1 B3 15
  • 16. Unidirectional 1-2-Many Between Entities... (Set Semantics) DELETE operation If join column is nullable, 1 update query for setting a_id = null. Else If orphanRemoval = false No changes would be made. Else Completely delete the row in B. A B Id name Id a_id Name 1 A1 1 1 B1 2 1 B2 3 1 B3 16
  • 17. Unidirectional 1-2-Many Between Entities... (Bag Semantics) Similar to SET semantics... A B Id name Id a_id Name 1 A1 1 1 B1 2 1 B2 3 1 B3 17
  • 18. Unidirectional 1-2-Many With Value Type (Bag Semantics) INSERT, DELETE, UPDATE operations 1. Select * from B. 2. Delete * from B where a_id = 1. 3. Insert into B all rows – along with new rows (in case of INSERT), or except rows to be delete (in case of DELETE). A B Id name a_id Name 1 A1 1 B1 1 B2 1 B3 18
  • 19. Unidirectional 1-2-Many With Value Type (Set Semantics) INSERT operation 1. Select * from B. 2. Insert into B the new rows to be added. A B Id name a_id Name 1 A1 1 B1 1 B2 1 B3 19
  • 20. Unidirectional 1-2-Many With Value Type (Set Semantics) DELETE operation 1. Select * from B. 2. Delete from B where a_id = 1 and name = ? A B Id name a_id Name 1 A1 1 B1 1 B2 1 B3 20
  • 21. Unidirectional 1-2-Many With Value Type (Set Semantics) UPDATE operation 1. Select * from B. 2. Delete the row to be updated. 3. Insert the newly updated object. A B Id name a_id Name 1 A1 1 B1 1 B2 1 B3 21
  • 22. Unidirectional 1-2-Many With Value Type (List Semantics) INSERT operation 1. Select * from B. 2. Update idx values in B. 3. Insert the new object. A B Id name a_id Name idx 1 A1 1 B1 0 1 B2 1 1 B3 2 22
  • 23. Unidirectional 1-2-Many With Value Type (List Semantics) DELETE operation 1. Select * from B. 2. Delete from B where idx = ? 3. Update the idx of other rows. A B Id name a_id Name idx 1 A1 1 B1 0 1 B2 1 1 B3 2 23
  • 24. Unidirectional 1-2-Many With Value Type (List Semantics) UPDATE operation Doesn’t seem to work!!! A B Id name a_id Name idx 1 A1 1 B1 0 1 B2 1 1 B3 2 24
  • 25. Unidirectional 1-2-1 Between Entities @OneToOne • Defaults to eager fetching. • To force lazy loading, use: @OneToOne(fetch=FetchType.LAZY) A B Id name b_id id Name 1 A1 1 1 B1 25
  • 26. Fetch Modes SELECT FETCH (Default) • Force lazy loading. JOIN FETCH • If join column nullable, then outer join, otherwise inner join. • Force eager fetching. BATCH-SIZE N • Doesn’t define how many records inside in the collections are loaded. Instead, it defines how many collections should be loaded. • Nice for nested tree node loading. SUBSELECT • Not only loads this collection in the second SELECT (either lazy or non-lazy), but also all other collections for all "owning" entities loaded in the first SELECT. 26
  • 27. Fetch Modes... BATCH-SIZE N Example List<A> aList = getList(); for (A a : aList) { List<B> bList = a.getbList(); } In Batch-size = 5, the select query would be: select ... from B where a_id in (?, ?, ?, ?, ?) A B id name a_id Name 1 A1 1 B1 2 A2 1 B2 2 B3 27
  • 28. Fetch Modes... SUBSELECT Example List<A> aList = getList(); for (A a : aList) { List<B> bList = a.getbList(); } In subselect, the select query would be: select ... from B where a_id in (select id from A) A B id name a_id Name 1 A1 1 B1 2 A2 1 B2 2 B3 28
  • 29. References • A Short Primer On Fetching Strategies: https://community.jboss.org/wiki/AShortPrimerO nFetchingStrategies • Hibernate – fetching strategies examples http://www.mkyong.com/hibernate/hibernate- fetching-strategies-examples/ • Bag is recommended over set: http://stackoverflow.com/questions/1505874/hib ernate-best-collection-type-to-use-bag-idbag-set- list-map 29