SlideShare a Scribd company logo
How to effectively shape the
@OneToMany association
https://github.com/AnghelLeonard/Hibernate-SpringBoot
Best Practices
https://github.com/AnghelLeonard/Hibernate-SpringBoot
• Use bidirectional @OneToMany
• Always cascade from parent-side to child-side
• Don’t forget to set mappedBy on the parent-side
• Set orphanRemoval on the parent-side
• Keep both sides of the association in sync
• Use lazy fetching on both sides of the association
• Override equals() and hashCode()
• Pay attention on overriding toString()
Best Practices
https://github.com/AnghelLeonard/Hibernate-SpringBoot
• Use bidirectional @OneToMany
• Always cascade from parent-side to child-side
• Don’t forget to set mappedBy on the parent-side
• Set orphanRemoval on the parent-side
• Keep both sides of the association in sync
• Use lazy fetching on both sides of the association
• Override equals() and hashCode()
• Pay attention on overriding toString()
Use bidirectional @OneToMany and avoid using
unidirectional @OneToMany. The unidirectional
@OneToMany comes with significant performance penalties
discussed in Spring Boot Persistence Best Practices book.
parent-side
child-side
Use bidirectional @OneToMany
https://github.com/AnghelLeonard/Hibernate-SpringBoot
Best Practices
• Use bidirectional @OneToMany
• Always cascade from parent-side to child-side
• Don’t forget to set mappedBy on the parent-side
• Set orphanRemoval on the parent-side
• Keep both sides of the association in sync
• Use lazy fetching on both sides of the association
• Override equals() and hashCode()
• Pay attention on overriding toString()Cascading from child-side to parent-side is a code smell and bad practice
and it is a clear signal that it is time to review your Domain Model and
application design. Think how improper or illogical is for a child to cascade
the creation of its parent! On one hand, a child cannot exists without a
parent, while, on the other hand, the child cascades the creation of his
parent. This is not logical, right? So, as a rule of thumb, always cascade from
parent-side to child-side.
parent-side
Always cascade from parent-side to child-side
https://github.com/AnghelLeonard/Hibernate-SpringBoot
Best Practices
• Use bidirectional @OneToMany
• Always cascade from parent-side to child-side
• Don’t forget to set mappedBy on the parent-side
• Set orphanRemoval on the parent-side
• Keep both sides of the association in sync
• Use lazy fetching on both sides of the association
• Override equals() and hashCode()
• Pay attention on overriding toString()The mappedBy attribute characterizes a bidirectional association and must
be set on the parent-side. In other words, for a bidirectional @OneToMany
association, set mappedBy to @OneToMany on the parent-side and add
@ManyToOne on the child-side referenced by mappedBy. Via mappedBy,
the bidirectional @OneToMany association signals that it mirrors the
@ManyToOne child-side mapping.
parent-side
Don’t forget to set mappedBy on the parent-side
https://github.com/AnghelLeonard/Hibernate-SpringBoot
Best Practices
https://github.com/AnghelLeonard/Hibernate-SpringBoot
• Use bidirectional @OneToMany
• Always cascade from parent-side to child-side
• Don’t forget to set mappedBy on the parent-side
• Set orphanRemoval on the parent-side
• Keep both sides of the association in sync
• Use lazy fetching on both sides of the association
• Override equals() and hashCode()
• Pay attention on overriding toString()Setting orphanRemoval on the parent-side guarantees the removal of
children without references. In other words, orphanRemoval is good for
cleaning up dependent objects that should not exist without a reference
from an owner object.
parent-side
Set orphanRemoval on the parent-side
https://github.com/AnghelLeonard/Hibernate-SpringBoot
Best Practices
• Use bidirectional @OneToMany
• Always cascade from parent-side to child-side
• Don’t forget to set mappedBy on the parent-side
• Set orphanRemoval on the parent-side
• Keep both sides of the association in sync
• Use lazy fetching on both sides of the association
• Override equals() and hashCode()
• Pay attention on overriding toString()
Keeping both sides of the association in sync can be easily accomplished via
helper methods added on the parent-side. Commonly, an addChild(),
removeChild() and removeChildren() methods will do the job pretty well. If
we don't strive to keep both sides of the association in sync then the entity
state transitions may lead to unexpected behaviors.
parent-side
Keep both sides of association in sync
Best Practices
• Use bidirectional @OneToMany
• Always cascade from parent-side to child-side
• Don’t forget to set mappedBy on the parent-side
• Set orphanRemoval on the parent-side
• Keep both sides of the association in sync
• Use lazy fetching on both sides of the association
• Override equals() and hashCode()
• Pay attention on overriding toString()
By default, fetching a parent-side entity will not fetch the children entities. This
means that @OneToMany is set to lazy. On the other hand, by default, fetching a
child entity will eagerly fetch its parent-side entity. It is advisable to explicitly set
@ManyToOne to lazy and rely on eager fetching only on query-basis.
child-side
Use lazy fetching on both sides of the association
Best Practices
• Use bidirectional @OneToMany
• Always cascade from parent-side to child-side
• Don’t forget to set mappedBy on the parent-side
• Set orphanRemoval on the parent-side
• Keep both sides of the association in sync
• Use lazy fetching on both sides of the association
• Override equals() and hashCode()
• Pay attention on overriding toString()
By properly overriding equals() and hashCode() methods, the
application obtains the same results across all entity state transitions.
For @OneToMany association, these methods should be overridden on
the child-side.
child-side
Override equals() and hashCode()
This is the best
way to override
equals() and
hashCode() in
entities via the
auto-generated
identifier (id).
More details are
available here.
Best Practices
• Use bidirectional @OneToMany
• Always cascade from parent-side to child-side
• Don’t forget to set mappedBy on the parent-side
• Set orphanRemoval on the parent-side
• Keep both sides of the association in sync
• Override equals() and hashCode()
• Use lazy fetching on both sides of the association
• Pay attention on overriding toString()
If toString() needs to be overridden, then pay attention to involve only the
basic attributes fetched when the entity is loaded from the database. Involving
lazy attributes or associations will trigger separate SQL statements for fetching
the corresponding data or will throw LazyInitializationException.
A complete example is available on GitHub
https://github.com/AnghelLeonard/Hibernate-SpringBoot
This was just 1 persistent performance item!
Check out 140+ in my book,
Spring Boot Persistence Best Practices
Let’s meet on Twitter
@anghelleonard
https://github.com/AnghelLeonard/Hibernate-SpringBoot

More Related Content

What's hot

Threat Hunting with Splunk
Threat Hunting with SplunkThreat Hunting with Splunk
Threat Hunting with Splunk
Splunk
 
資訊安全入門
資訊安全入門資訊安全入門
資訊安全入門
Tyler Chen
 
窺探職場上所需之資安專業技術與能力 Tdohconf
窺探職場上所需之資安專業技術與能力 Tdohconf窺探職場上所需之資安專業技術與能力 Tdohconf
窺探職場上所需之資安專業技術與能力 Tdohconf
jack51706
 

What's hot (20)

Click jacking
Click jackingClick jacking
Click jacking
 
BlueHat v17 || Dangerous Contents - Securing .Net Deserialization
BlueHat v17 || Dangerous Contents - Securing .Net Deserialization BlueHat v17 || Dangerous Contents - Securing .Net Deserialization
BlueHat v17 || Dangerous Contents - Securing .Net Deserialization
 
Understanding low latency jvm gcs
Understanding low latency jvm gcsUnderstanding low latency jvm gcs
Understanding low latency jvm gcs
 
Attacker's Perspective of Active Directory
Attacker's Perspective of Active DirectoryAttacker's Perspective of Active Directory
Attacker's Perspective of Active Directory
 
Threat Hunting with Splunk
Threat Hunting with SplunkThreat Hunting with Splunk
Threat Hunting with Splunk
 
OWASP AppSecEU 2018 – Attacking "Modern" Web Technologies
OWASP AppSecEU 2018 – Attacking "Modern" Web TechnologiesOWASP AppSecEU 2018 – Attacking "Modern" Web Technologies
OWASP AppSecEU 2018 – Attacking "Modern" Web Technologies
 
C++でNVMeと(*´Д`)ハァハァ 戯れていたら一年経ってた。
C++でNVMeと(*´Д`)ハァハァ 戯れていたら一年経ってた。C++でNVMeと(*´Д`)ハァハァ 戯れていたら一年経ってた。
C++でNVMeと(*´Д`)ハァハァ 戯れていたら一年経ってた。
 
Sinatra Rack And Middleware
Sinatra Rack And MiddlewareSinatra Rack And Middleware
Sinatra Rack And Middleware
 
Talking About SSRF,CRLF
Talking About SSRF,CRLFTalking About SSRF,CRLF
Talking About SSRF,CRLF
 
Red Team Methodology - A Naked Look
Red Team Methodology - A Naked LookRed Team Methodology - A Naked Look
Red Team Methodology - A Naked Look
 
Spring Framework 튜토리얼 - 네이버 최영목님
Spring Framework 튜토리얼 - 네이버 최영목님Spring Framework 튜토리얼 - 네이버 최영목님
Spring Framework 튜토리얼 - 네이버 최영목님
 
Introduction to red team operations
Introduction to red team operationsIntroduction to red team operations
Introduction to red team operations
 
Golang Restful 서버 개발기
Golang Restful 서버 개발기Golang Restful 서버 개발기
Golang Restful 서버 개발기
 
XSS Magic tricks
XSS Magic tricksXSS Magic tricks
XSS Magic tricks
 
Running Spring Boot Applications as GraalVM Native Images
Running Spring Boot Applications as GraalVM Native ImagesRunning Spring Boot Applications as GraalVM Native Images
Running Spring Boot Applications as GraalVM Native Images
 
Борьба с фишингом. Пошаговая инструкция
Борьба с фишингом. Пошаговая инструкцияБорьба с фишингом. Пошаговая инструкция
Борьба с фишингом. Пошаговая инструкция
 
資訊安全入門
資訊安全入門資訊安全入門
資訊安全入門
 
Super Easy Memory Forensics
Super Easy Memory ForensicsSuper Easy Memory Forensics
Super Easy Memory Forensics
 
オブジェクト指向とは何ですか?
オブジェクト指向とは何ですか?オブジェクト指向とは何ですか?
オブジェクト指向とは何ですか?
 
窺探職場上所需之資安專業技術與能力 Tdohconf
窺探職場上所需之資安專業技術與能力 Tdohconf窺探職場上所需之資安專業技術與能力 Tdohconf
窺探職場上所需之資安專業技術與能力 Tdohconf
 

Recently uploaded

Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
mbmh111980
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
Alluxio, Inc.
 

Recently uploaded (20)

Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
Studiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareStudiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting software
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM Integration
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdf
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning Framework
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysis
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
 

Spring Boot Persistence Best Practices - How to effectively shape the @OneToMany association

  • 1.
  • 2. How to effectively shape the @OneToMany association https://github.com/AnghelLeonard/Hibernate-SpringBoot
  • 3. Best Practices https://github.com/AnghelLeonard/Hibernate-SpringBoot • Use bidirectional @OneToMany • Always cascade from parent-side to child-side • Don’t forget to set mappedBy on the parent-side • Set orphanRemoval on the parent-side • Keep both sides of the association in sync • Use lazy fetching on both sides of the association • Override equals() and hashCode() • Pay attention on overriding toString()
  • 4. Best Practices https://github.com/AnghelLeonard/Hibernate-SpringBoot • Use bidirectional @OneToMany • Always cascade from parent-side to child-side • Don’t forget to set mappedBy on the parent-side • Set orphanRemoval on the parent-side • Keep both sides of the association in sync • Use lazy fetching on both sides of the association • Override equals() and hashCode() • Pay attention on overriding toString() Use bidirectional @OneToMany and avoid using unidirectional @OneToMany. The unidirectional @OneToMany comes with significant performance penalties discussed in Spring Boot Persistence Best Practices book.
  • 6. Best Practices • Use bidirectional @OneToMany • Always cascade from parent-side to child-side • Don’t forget to set mappedBy on the parent-side • Set orphanRemoval on the parent-side • Keep both sides of the association in sync • Use lazy fetching on both sides of the association • Override equals() and hashCode() • Pay attention on overriding toString()Cascading from child-side to parent-side is a code smell and bad practice and it is a clear signal that it is time to review your Domain Model and application design. Think how improper or illogical is for a child to cascade the creation of its parent! On one hand, a child cannot exists without a parent, while, on the other hand, the child cascades the creation of his parent. This is not logical, right? So, as a rule of thumb, always cascade from parent-side to child-side.
  • 7. parent-side Always cascade from parent-side to child-side https://github.com/AnghelLeonard/Hibernate-SpringBoot
  • 8. Best Practices • Use bidirectional @OneToMany • Always cascade from parent-side to child-side • Don’t forget to set mappedBy on the parent-side • Set orphanRemoval on the parent-side • Keep both sides of the association in sync • Use lazy fetching on both sides of the association • Override equals() and hashCode() • Pay attention on overriding toString()The mappedBy attribute characterizes a bidirectional association and must be set on the parent-side. In other words, for a bidirectional @OneToMany association, set mappedBy to @OneToMany on the parent-side and add @ManyToOne on the child-side referenced by mappedBy. Via mappedBy, the bidirectional @OneToMany association signals that it mirrors the @ManyToOne child-side mapping.
  • 9. parent-side Don’t forget to set mappedBy on the parent-side https://github.com/AnghelLeonard/Hibernate-SpringBoot
  • 10. Best Practices https://github.com/AnghelLeonard/Hibernate-SpringBoot • Use bidirectional @OneToMany • Always cascade from parent-side to child-side • Don’t forget to set mappedBy on the parent-side • Set orphanRemoval on the parent-side • Keep both sides of the association in sync • Use lazy fetching on both sides of the association • Override equals() and hashCode() • Pay attention on overriding toString()Setting orphanRemoval on the parent-side guarantees the removal of children without references. In other words, orphanRemoval is good for cleaning up dependent objects that should not exist without a reference from an owner object.
  • 11. parent-side Set orphanRemoval on the parent-side https://github.com/AnghelLeonard/Hibernate-SpringBoot
  • 12. Best Practices • Use bidirectional @OneToMany • Always cascade from parent-side to child-side • Don’t forget to set mappedBy on the parent-side • Set orphanRemoval on the parent-side • Keep both sides of the association in sync • Use lazy fetching on both sides of the association • Override equals() and hashCode() • Pay attention on overriding toString() Keeping both sides of the association in sync can be easily accomplished via helper methods added on the parent-side. Commonly, an addChild(), removeChild() and removeChildren() methods will do the job pretty well. If we don't strive to keep both sides of the association in sync then the entity state transitions may lead to unexpected behaviors.
  • 13. parent-side Keep both sides of association in sync
  • 14. Best Practices • Use bidirectional @OneToMany • Always cascade from parent-side to child-side • Don’t forget to set mappedBy on the parent-side • Set orphanRemoval on the parent-side • Keep both sides of the association in sync • Use lazy fetching on both sides of the association • Override equals() and hashCode() • Pay attention on overriding toString() By default, fetching a parent-side entity will not fetch the children entities. This means that @OneToMany is set to lazy. On the other hand, by default, fetching a child entity will eagerly fetch its parent-side entity. It is advisable to explicitly set @ManyToOne to lazy and rely on eager fetching only on query-basis.
  • 15. child-side Use lazy fetching on both sides of the association
  • 16. Best Practices • Use bidirectional @OneToMany • Always cascade from parent-side to child-side • Don’t forget to set mappedBy on the parent-side • Set orphanRemoval on the parent-side • Keep both sides of the association in sync • Use lazy fetching on both sides of the association • Override equals() and hashCode() • Pay attention on overriding toString() By properly overriding equals() and hashCode() methods, the application obtains the same results across all entity state transitions. For @OneToMany association, these methods should be overridden on the child-side.
  • 17. child-side Override equals() and hashCode() This is the best way to override equals() and hashCode() in entities via the auto-generated identifier (id). More details are available here.
  • 18. Best Practices • Use bidirectional @OneToMany • Always cascade from parent-side to child-side • Don’t forget to set mappedBy on the parent-side • Set orphanRemoval on the parent-side • Keep both sides of the association in sync • Override equals() and hashCode() • Use lazy fetching on both sides of the association • Pay attention on overriding toString() If toString() needs to be overridden, then pay attention to involve only the basic attributes fetched when the entity is loaded from the database. Involving lazy attributes or associations will trigger separate SQL statements for fetching the corresponding data or will throw LazyInitializationException.
  • 19. A complete example is available on GitHub https://github.com/AnghelLeonard/Hibernate-SpringBoot
  • 20. This was just 1 persistent performance item! Check out 140+ in my book, Spring Boot Persistence Best Practices
  • 21. Let’s meet on Twitter @anghelleonard https://github.com/AnghelLeonard/Hibernate-SpringBoot