SlideShare a Scribd company logo
Effiziente Persistierung
mit Hibernate
www.thoughts-on-java.org
www.thoughts-on-java.org
CDI 2.0 Expert
Group Member
Independent
author and
trainer
www.thoughts-on-java.org
@thjanssen123
/c/ThoughtsOnJava
/ThoughtsOnJava
HibernateTips
More than 70 solutions to common
Hibernate problems
www.hibernate-tips.com
ThorbenJanssen
Application
www.thoughts-on-java.org
Performance
www.thoughts-on-java.org
Performance
• Recognize performance problems as early as possible
• Typical causes for performance problems
• Solving performance problems
www.thoughts-on-java.org
Hibernate Statistics
www.thoughts-on-java.org
HibernateStatistics
• Activate via system property
• hibernate.generate_statistics = true
• Configure logging
• org.hibernate.stat = DEBUG
www.thoughts-on-java.org
www.thoughts-on-java.org
Demo
Typical causes for performance
problems
www.thoughts-on-java.org
TypicalCauses • Slow SELECT statements
• Wrong FetchType
• Load same data multiple times
• Delete or edit records one by one
• Put logic into the application instead of the database/query
www.thoughts-on-java.org
Slow SELECT-statements
www.thoughts-on-java.org
SlowSELECTs • In general no „real“ JPA or Hibernate problem
• Check generated SQL
• Check execution plan of the statement
• Check indexes
• Optimize SELECT statement
• Consider to use a native query
www.thoughts-on-java.org
NativeQuery • Reasons to use native queries:
• JPQL supports only a subset of SQL
• Database specific features
• Native queries return an Object[] for each row
• Needs to be mapped programmatically or declaratively
www.thoughts-on-java.org
www.thoughts-on-java.org
Demo
FetchType
www.thoughts-on-java.org
FetchType
• Defines when the relationship will be fetched
• Static definition in entity mapping
www.thoughts-on-java.org
@ManyToMany(mappedBy="authors", fetch = FetchType.EAGER)
private Set<Book> books;
FetchType • Lazy
• Relationship gets loaded at first access
• Default for to-many relationships
• Eager
• Loads relationships immediately
• Default for to-one relationships
www.thoughts-on-java.org
Recommendation
s• To-many relationships
• Stick to the default mapping (FetchType.LAZY)
• Use eager fetching for specific queries, if required
• To-one relationships
• Check individually
• Default is fine in most of the cases
www.thoughts-on-java.org
Query Specific Fetching
www.thoughts-on-java.org
N+1Select? • Most common cause for performance problems
• Lazy fetching of related entities creates too many queries
www.thoughts-on-java.org
List<Author> authors = this.em.createQuery("SELECT a FROM Author a",
Author.class).getResultList();
for (Author a : authors) {
System.out.println("Author " + a.getFirstName() + " " + a.getLastName()
+ " wrote " + a.getBooks().size() + “ Books.”));
}
Queryspecificfetching
• Fetch all required entities with one query
• Fetch Joins
• @NamedEntityGraph
• EntityGraph
www.thoughts-on-java.org
Fetch Join
www.thoughts-on-java.org
FetchJoin
• Use JOIN FETCH instead of JOIN in JPQL query
www.thoughts-on-java.org
List<Author> authors = this.em.createQuery(
"SELECT DISTINCT a FROM Author a JOIN FETCH a.books b",
Author.class).getResultList();
www.thoughts-on-java.org
Demo
FetchJoin • Advantages
• Relationships gets loaded in same query
• Disadvantages
• Requires a special query for each use case
• Creates cartesian product
www.thoughts-on-java.org
NamedEntityGraph
www.thoughts-on-java.org
NamedEntityGrap
h• Introduced in JPA 2.1
• Declaratively defines a graph of entities which will be loaded
• Graph is query independent
www.thoughts-on-java.org
www.thoughts-on-java.org
Demo
NamedEntityGrap
h• Fetch graph
• Eager loading for all elements of the graph
• Lazy loading for all other attributes
• Load graph
• Eager loading for all elements of the graph
• Loads all other attributes with their defined FetchType
• Hibernate always uses a load graph
• HHH-8776
www.thoughts-on-java.org
NamedEntityGrap
h• Advantages
• Query specific EAGER loading
• Definition of the graph is independent of the query
• Disadvantages
• Creates cartesian product
www.thoughts-on-java.org
EntityGraph
www.thoughts-on-java.org
EntityGraph • Introduced in JPA 2.1
• Dynamic version of @NamedEntityGraph
• Definition via Java API
• Graph is query independent
www.thoughts-on-java.org
EntityGraph • Define and use EntityGraph
www.thoughts-on-java.org
EntityGraph graph = this.em.createEntityGraph(Author.class);
Subgraph<Book> bookSubGraph = graph.addSubgraph(Author_.books);
bookSubGraph.addSubgraph(Book_.reviews);
this.em.createQuery("SELECT DISTINCT a FROM Author a")
.setHint("javax.persistence.loadgraph", graph);
EntityGraph • Advantages
• Query specific EAGER loading
• Definition of the graph is independent of the query
• Dynamic creation at runtime
• Disadvantages
• Creates cartesian product
www.thoughts-on-java.org
Caching
www.thoughts-on-java.org
Query
Cache
Caches
www.thoughts-on-java.org
DB
2nd
Level
Cache
1st
Level
Cache
Hibernate
Session
1st
Level
Cache
Hibernate
Session
1st Level Cache
www.thoughts-on-java.org
1stLevelCache
• Activated by default
• Linked to the Hibernate session
• Stores all entities that were used within a session
• Transparent usage
www.thoughts-on-java.org
2nd Level Cache
www.thoughts-on-java.org
2ndLevelCache • Session independent entity store
• Needs to be activated
• persistence.xml or EntityManagerFactory
• Transparent usage
• PersistenceProvider doesn‘t need to provide it
• Not always portable
www.thoughts-on-java.org
2ndLevelCache • Shared Cache Mode
• ALL cache all entities
• NONE cache no entities
• ENABLE_SELECTIVE cache needs to be activated for
specific entities
• DISABLE_SELECTIVE cache can be deactivated for specific
entities
• UNSPECIFIED use default settings of the
PersistenceProvider
www.thoughts-on-java.org
www.thoughts-on-java.org
Demo
2ndLevelCache • Cache configuration
• Cache Retrieve Mode
• How to read entities from the cache
• Cache Store Mode
• How to write entities to the cache
• Concurrency Strategy
• How to handle concurrent access
www.thoughts-on-java.org
Query Cache
www.thoughts-on-java.org
QueryCache • Hibernate specific
• Stores query result session independent
• Needs to be activated (persistence.xml)
• hibernate.cache.use_query_cache = true
• Activate caching for a specific query
• org.hibernate.Query.setCacheable(true)
• @NamedQuery(… hints =
@QueryHint(name="org.hibernate.cacheable", value="true"))
www.thoughts-on-java.org
QueryCache • Stores query results for a query and its parameters
• [„FROM AuthorWHERE id=?“, 1]  [1]
• Stores only entity references or scalars
• Always use together with 2nd Level Cache
www.thoughts-on-java.org
www.thoughts-on-java.org
Demo
Recommendation
s• Only cache data that is seldom updated
• Always benchmark the application when adding or changing
caching
• Use Query Cache together with 2nd Level Cache
• Configuration has to fit to each other
www.thoughts-on-java.org
www.thoughts-on-java.org
thoughts-on-java.org
@thjanssen123
/c/ThoughtsOnJava
/ThoughtsOnJava
HibernateTips
More than 70 solutions to common
Hibernate problems
www.hibernate-tips.com
Online & Inhouse
Training
Coaching &
Consulting

More Related Content

What's hot (20)

PPTX
Effiziente persistierung
Thorben Janssen
 
PPTX
Battle of the Giants round 2
Rafał Kuć
 
PPT
Performance Tuning with JPA 2.1 and Hibernate (Geecon Prague 2015)
Thorben Janssen
 
PDF
Cassandra rapid prototyping with achilles
Duyhai Doan
 
PDF
ORM Pink Unicorns
Ortus Solutions, Corp
 
PDF
Killing Shark-Riding Dinosaurs with ORM
Ortus Solutions, Corp
 
PPTX
Examiness hints and tips from the trenches
Ismail Mayat
 
PPTX
Real World MVC
James Johnson
 
PPT
Presentation
Manav Prasad
 
PDF
Cassandra java libraries
Duyhai Doan
 
PDF
State of search | drupalcon dublin
Joris Vercammen
 
PDF
初心者向けGAE/Java説明資料
Shinichi Ogawa
 
PPT
Jsp
Manav Prasad
 
PDF
Doing Drupal security right from Drupalcon London
Gábor Hojtsy
 
PPT
Solr and Elasticsearch, a performance study
Charlie Hull
 
PDF
Workshop: Learning Elasticsearch
Anurag Patel
 
PDF
Green dao
Droidcon Berlin
 
PPTX
What You Missed in Computer Science
Taylor Lovett
 
PPTX
GreenDao Introduction
Booch Lin
 
PPTX
JNoSQL: The Definitive Solution for Java and NoSQL Databases
Werner Keil
 
Effiziente persistierung
Thorben Janssen
 
Battle of the Giants round 2
Rafał Kuć
 
Performance Tuning with JPA 2.1 and Hibernate (Geecon Prague 2015)
Thorben Janssen
 
Cassandra rapid prototyping with achilles
Duyhai Doan
 
ORM Pink Unicorns
Ortus Solutions, Corp
 
Killing Shark-Riding Dinosaurs with ORM
Ortus Solutions, Corp
 
Examiness hints and tips from the trenches
Ismail Mayat
 
Real World MVC
James Johnson
 
Presentation
Manav Prasad
 
Cassandra java libraries
Duyhai Doan
 
State of search | drupalcon dublin
Joris Vercammen
 
初心者向けGAE/Java説明資料
Shinichi Ogawa
 
Doing Drupal security right from Drupalcon London
Gábor Hojtsy
 
Solr and Elasticsearch, a performance study
Charlie Hull
 
Workshop: Learning Elasticsearch
Anurag Patel
 
Green dao
Droidcon Berlin
 
What You Missed in Computer Science
Taylor Lovett
 
GreenDao Introduction
Booch Lin
 
JNoSQL: The Definitive Solution for Java and NoSQL Databases
Werner Keil
 

Similar to Hibernate Performance Tuning @JUG Thüringen (20)

PDF
Building Fast and Scalable Persistence Layers with Spring Data JPA
VMware Tanzu
 
PDF
Hibernate performance tuning
Igor Dmitriev
 
PDF
Hibernate ORM: Tips, Tricks, and Performance Techniques
Brett Meyer
 
DOC
Advanced Hibernate Notes
Kaniska Mandal
 
PDF
Lazy vs. Eager Loading Strategies in JPA 2.1
Patrycja Wegrzynowicz
 
PDF
JPA 2.1 performance tuning tips
osa_ora
 
PPT
Hibernate jj
Joe Jacob
 
PPT
Accelerated data access
gordonyorke
 
PPTX
Tips about hibernate with spring data jpa
Thiago Dos Santos Hora
 
KEY
Hibernate Performance Tuning (JEEConf 2012)
Sander Mak (@Sander_Mak)
 
PPTX
Hibernate in XPages
Toby Samples
 
PDF
Second Level Cache in JPA Explained
Patrycja Wegrzynowicz
 
PPT
Hibernate for Beginners
Ramesh Kumar
 
PDF
Java persistence api 2.1
Rakesh K. Cherukuri
 
PDF
Hibernate caching
Alex Verdyan
 
PDF
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
Ortus Solutions, Corp
 
PDF
Jpa
vantinhkhuc
 
PDF
Advance Features of Hibernate
Mindfire Solutions
 
PDF
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
Building Fast and Scalable Persistence Layers with Spring Data JPA
VMware Tanzu
 
Hibernate performance tuning
Igor Dmitriev
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Brett Meyer
 
Advanced Hibernate Notes
Kaniska Mandal
 
Lazy vs. Eager Loading Strategies in JPA 2.1
Patrycja Wegrzynowicz
 
JPA 2.1 performance tuning tips
osa_ora
 
Hibernate jj
Joe Jacob
 
Accelerated data access
gordonyorke
 
Tips about hibernate with spring data jpa
Thiago Dos Santos Hora
 
Hibernate Performance Tuning (JEEConf 2012)
Sander Mak (@Sander_Mak)
 
Hibernate in XPages
Toby Samples
 
Second Level Cache in JPA Explained
Patrycja Wegrzynowicz
 
Hibernate for Beginners
Ramesh Kumar
 
Java persistence api 2.1
Rakesh K. Cherukuri
 
Hibernate caching
Alex Verdyan
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
Ortus Solutions, Corp
 
Advance Features of Hibernate
Mindfire Solutions
 
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
Ad

Recently uploaded (20)

PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PDF
AOMEI Partition Assistant Crack 10.8.2 + WinPE Free Downlaod New Version 2025
bashirkhan333g
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
PPTX
Comprehensive Risk Assessment Module for Smarter Risk Management
EHA Soft Solutions
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
Customise Your Correlation Table in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
AOMEI Partition Assistant Crack 10.8.2 + WinPE Free Downlaod New Version 2025
bashirkhan333g
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
Comprehensive Risk Assessment Module for Smarter Risk Management
EHA Soft Solutions
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Customise Your Correlation Table in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Ad

Hibernate Performance Tuning @JUG Thüringen

Editor's Notes

  • #2: 1
  • #21: The n+1 select issue is the most common cause for JPA related performance issues. It describes the inefficiency that occurs, if the persistence provider needs to perform additional queries to initialize lazy fetched relationships to other entities. Click Like in this code snippet. As you can see, the query in the first line selects all authors from the database and we then iterate through all of them and print out their names and the number of books they have written. This simple code snippet creates n+1 queries, if FetchType.LAZY is used for the relationship between the Author and the Book entities. In that case, Hibernate or any other JPA persistence provider, needs to perform an additional query in each iteration to get the Books of that Author from the database. So in the end, Hibernate performs n+1 queries. 1 to get n Authors from the database and additional n queries to initialize the Books relationship.