SlideShare a Scribd company logo
Hibernate ORM:
Tips, Tricks, and
Performance Techniques
Brett Meyer
Senior Software Engineer
Hibernate ORM, Red Hat
Brett Meyer
• Hibernate ORM
– ORM 4 & 5 development
– Hibernate OSGi
– Developer community engagement
– Red Hat enterprise support, Hibernate engineering lead

• Other contributions
– Apache Camel
– Infinispan

• Contact me
– @brettemeyer or +brettmeyer
– Freenode #hibernate or #hibernate-dev (brmeyer)
github.com/brmeyer
/HibernateDemos

slideshare.net/brmeyer
ORM? JPA?
• ORM: Object/Relational Mapping
– Persistence: Data objects outlive the JVM app
– Maps Java POJOs to relational databases
– Supports OO concepts: inheritance, object identity, etc.
– Navigate data by walking the object graph, not the explicit
relational model

• JPA: Java Persistence API
• Hibernate ORM provides its own native API, in
addition to full JPA support
• Annotations and XML
Overview
•
•
•
•
•
•
•
•

Fetching Strategies
2nd Level Entity Cache
Query Cache
Cache Management
Bytecode Enhancement
Hibernate Search
Misc. Tips
Q&A
Caveats
• No “one strategy to rule them all”
• Varies greatly between apps
• Important to understand concepts, then
apply as necessary
• Does not replace database tuning!
First, the antithesis:
public User get(String username) {
final Session session = openSession();
session.getTransaction().begin();
final User user = (User) session.get( User.class, username );
session.getTransaction().commit();
return user;
}
public boolean login(String username) {
return get(username) != null;
}

Clean? Yes. But...
EAGER Demo
• Prototypes start “simple”
– EAGER
– No caching
– Overuse of the kitchen sink

• DAO looks clean
• Then you see the SQL logs
Fetching Strategies
Fetching Strategies
• By far, the most frequent mistake
• Also the most costly
• 2 concepts:
– WHEN (fetch timing)
– HOW (fetch style)
WHEN (fetch timing)
Fetch Timing: EAGER
•
•
•
•

Immediate
Can be convenient (in some ways)
Significantly increases payload
Enormous amount of unnecessary
fetches for deep association tree
Fetch Timing: LAZY
• Fetched when first accessed
• Collections
– LAZY by default
– Utilizes Hibernate's internal concept of “persistent
collections”
– DEMO

• Single attribute (basic)
– Requires bytecode enhancement
– Not typically used nor beneficial
Fetch Timing: LAZY (cont'd)
• Single (ToOne) associations
– Fetched when accessed
– Proxy
• Default
• Fetched when accessed (except ID)
• Handled internally by Hibernate

– No-proxy
• Fetched when accessed (including ID)
• No visible proxy
• Requires buildtime bytecode enhancement
Fetch Timing: EXTRA LAZY
•
•
•
•

Collections only
Fetch individual elements as accessed
Does not fetch entire collection
DEMO
HOW (fetch style)
Fetch Style: JOIN
• Join fetch (left/outer join)
• Great for ToOne associations
• Multiple collection joins
– Possible for non-bags
– Warning: Cartesian product! SELECT is
normally faster

• DEMO
Fetch Style: SELECT
• Follow-up selects
• Default style for collections (avoids
cartesian products)
• Can result in 1+N selects (fetch per
collection entry)
• DEMO
Fetch Style: BATCH
• Fetches multiple entries when one is
accessed
• Configurable on both class and collection
levels (“batch-size”)
• Simple select and list of keys
• Multiple algorithms (new as of 4.2)
• Determines # of entries to fetch, based on
# of provided keys
Fetch Style: BATCH (cont'd)
• Legacy: pre-determined sizes, rounded
down
– batch-size==25, 24 elements in collection
– Fetches -> 12, 10, 2

• Padded: same as Legacy, size rounded up
• Dynamic: builds SQL for the # of keys,
limited by “batch-size”
• DEMO
Fetch Style: SUBSELECT
• Follow-up select
• Fetches all collection entries when
accessed for the 1st time
• Original root entry select used as
subselect
• Performance depends on the DB itself
• DEMO
Fetch Style: PROFILE
• named profile defining fetch styles
• “activated” through the Session
@Entity
@FetchProfile(name = "customer-with-orders", fetchOverrides = {
@FetchProfile.FetchOverride(entity = Customer.class,
association = "orders", mode = FetchMode.JOIN)
})
public class Customer {
...
@OneToMany
private Set<Order> orders;
...
}
Session session = ...;
session.enableFetchProfile( "customer-with-orders" );
Customer customer = (Customer) session.get(
Customer.class, customerId );
Fetch Style Tips
• Best to leave defaults in mappings
• Define the style at the query level
• Granular control
nd

2 Level Entity
Cache (2LC)
2LC
• differs from the 1st level (Session)
• SessionFactory level (JVM)
• can scale horizontally on commodity
hardware (clustered)
• multiple providers
• currently focus on Infinispan (JBoss) &
EHCache (Terracotta)
2LC (cont'd)
• disabled by default
– can enable globally (not recommended)
– enable for individual entities and
collections
– configurable at the Session level w/
CacheMode

• cache all properties (default) or only
non-lazy
2LC (cont'd)
• Since JVM-level, concurrency is an issue
• Concurrency strategies
– Read only: simplest and optimal
– Read-write
• Supports updates
• Should not use for serializable transaction isolation

– Nonstrict-read-write
• If updates are occasional and unlikely to collide
• No strict transaction isolation

– Transactional:
• Fully transactional cache providers (ie, Infinispan and EHCache)
• JTA required
2LC (cont'd)
• DEMO
Query Cache
Query Cache
• Caches query result sets
• Repetitive queries with identical params
• Different from an entity cache
– Does not maintain entity state
– Holds on to sets of identifiers

• If used, best in conjunction with 2LC
Query Cache (cont'd)
• Disabled by default
• Many applications do not gain anything
• Queries invalidated upon relevant
updates
• Increases overhead by some: tracks
when to invalidate based on commits
• DEMO
Cache Management
Cache Management
• Entities stored in Session cache when saved,
updated, or retrieved
• Session#flush syncs all cached with DB
– Minimize usage

• Manage memory:
– Session#evict(entity) when no longer needed
– Session#clear for all
– Important for large dataset handling

• Same for 2LC, but methods on
SessionFactory#getCache
Bytecode
Enhancement
Bytecode Enhancement
• Not just for no-proxy, ToOne laziness
• Reduced load on PersistenceContext
– EntityEntry
• Internally provides state & Session association
• “Heavy” operation and typically a hotspot (multiple Maps)

– ManagedEntity
• Reduced memory and CPU loads
• Entities maintain their own state with bytecode enhancement
• (ManagedEntity)entity.$$_hibernate_getEntityEntry();

– 3 ways:
• Entity implements ManagedEntity and maintains the association
• Buildtime instrumentation (Ant and recently Gradle/Maven)
• Runtime instrumentation
Bytecode (cont'd)
• dirtiness checking
– Legacy: “dirtiness” determined by deep comparison of
entity state
– Enhancement: entity tracks its own dirtiness
– Simply check the flag (no deep comparison)
– Already mentioned…
• Minimize amount of flushes to begin with
• Minimize the # of entities in the cache -- evict when possible

• Many additional bytecode improvements planned
Hibernate Search
Hibernate Search
• Full-text search on the DB
– Bad performance
– CPU/IO overhead

• Offload full-text queries to Hibernate
Search engine
– Fully indexed
– Horizontally scalable

• Based on Apache Lucene
Hibernate Search (cont'd)
• Annotate entities with @Indexed
• Annotate properties with @Field
– Index the text: index=Index.YES
– “Analyze” the text: analyze=Analyze.YES
•
•
•
•

Lucene analyzer
Chunks sentences into words
Lowercase all of them
Exclude common words (“a”, “the”)

• Combo of indexing and analysis == performant
full-text searches!
Misc. Tips
Misc. Tips
• Easy to overlook unintended fetches
– Ex: Fully implemented toString with all
associations (fetches everything simply for
logging)

• Use @Immutable when possible
– Excludes entity from dirtiness checks
– Other internal optimizations
Misc. Tips (cont'd)
• Use Bag or List for inverse collections, not Set
– Collection#add & #addAll always return true (don't
need to check for pre-existing values)
– I.e., can add a value without fetching the collection
Parent p = (Parent) session.load(Parent.class, id);
Child c = new Child();
c.setParent(p);
p.addChild(c);
...
// does *not* fetch the collection
p.getChildren().add(c);
Misc. Tips (cont'd)
• One-shot delete (non-inverse collections)
– Scenario: 20 elements, need to delete 18 & add 3
– Default: Hibernate would delete the 18 one-byone, then add the 3
– Instead:
• Discard the entire collection (deletes all elements)
• Save a new collection with 5 elements
• 1 bulk delete SQL and 5 inserts

– Important concept for large amounts of data
How to Help:
hibernate.org
/orm/contribute
QUESTIONS?
•
•
•
•

Q&A
#hibernate or #hibernate-dev (brmeyer)
@brettemeyer
+brettmeyer

More Related Content

What's hot

Windows Registered I/O (RIO) vs IOCP
Windows Registered I/O (RIO) vs IOCPWindows Registered I/O (RIO) vs IOCP
Windows Registered I/O (RIO) vs IOCP
Seungmo Koo
 
[오픈소스컨설팅] EFK Stack 소개와 설치 방법
[오픈소스컨설팅] EFK Stack 소개와 설치 방법[오픈소스컨설팅] EFK Stack 소개와 설치 방법
[오픈소스컨설팅] EFK Stack 소개와 설치 방법
Open Source Consulting
 
Spring Boot
Spring BootSpring Boot
Spring Boot
koppenolski
 
HTTP Request Smuggling via higher HTTP versions
HTTP Request Smuggling via higher HTTP versionsHTTP Request Smuggling via higher HTTP versions
HTTP Request Smuggling via higher HTTP versions
neexemil
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
Xcat Liu
 
Vue.js
Vue.jsVue.js
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
Amazon Web Services Korea
 
[수정본] 우아한 객체지향
[수정본] 우아한 객체지향[수정본] 우아한 객체지향
[수정본] 우아한 객체지향
Young-Ho Cho
 
〈야생의 땅: 듀랑고〉 서버 아키텍처 Vol. 3
〈야생의 땅: 듀랑고〉 서버 아키텍처 Vol. 3〈야생의 땅: 듀랑고〉 서버 아키텍처 Vol. 3
〈야생의 땅: 듀랑고〉 서버 아키텍처 Vol. 3
Heungsub Lee
 
Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)
Ryan Cuprak
 
[OPD 2019] Attacking JWT tokens
[OPD 2019] Attacking JWT tokens[OPD 2019] Attacking JWT tokens
[OPD 2019] Attacking JWT tokens
OWASP
 
F5 ASM v12 DDoS best practices
F5 ASM v12 DDoS best practices F5 ASM v12 DDoS best practices
F5 ASM v12 DDoS best practices
Lior Rotkovitch
 
mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교Woo Yeong Choi
 
Pentesting Rest API's by :- Gaurang Bhatnagar
Pentesting Rest API's by :- Gaurang BhatnagarPentesting Rest API's by :- Gaurang Bhatnagar
Pentesting Rest API's by :- Gaurang Bhatnagar
OWASP Delhi
 
FIFA 온라인 3의 MongoDB 사용기
FIFA 온라인 3의 MongoDB 사용기FIFA 온라인 3의 MongoDB 사용기
FIFA 온라인 3의 MongoDB 사용기
Jongwon Kim
 
쿠키런 1년, 서버개발 분투기
쿠키런 1년, 서버개발 분투기쿠키런 1년, 서버개발 분투기
쿠키런 1년, 서버개발 분투기
Brian Hong
 
4. 대용량 아키텍쳐 설계 패턴
4. 대용량 아키텍쳐 설계 패턴4. 대용량 아키텍쳐 설계 패턴
4. 대용량 아키텍쳐 설계 패턴
Terry Cho
 
A story of the passive aggressive sysadmin of AEM
A story of the passive aggressive sysadmin of AEMA story of the passive aggressive sysadmin of AEM
A story of the passive aggressive sysadmin of AEM
Frans Rosén
 
대용량 분산 아키텍쳐 설계 #5. rest
대용량 분산 아키텍쳐 설계 #5. rest대용량 분산 아키텍쳐 설계 #5. rest
대용량 분산 아키텍쳐 설계 #5. rest
Terry Cho
 
CNIT 129S: Securing Web Applications Ch 1-2
CNIT 129S: Securing Web Applications Ch 1-2CNIT 129S: Securing Web Applications Ch 1-2
CNIT 129S: Securing Web Applications Ch 1-2
Sam Bowne
 

What's hot (20)

Windows Registered I/O (RIO) vs IOCP
Windows Registered I/O (RIO) vs IOCPWindows Registered I/O (RIO) vs IOCP
Windows Registered I/O (RIO) vs IOCP
 
[오픈소스컨설팅] EFK Stack 소개와 설치 방법
[오픈소스컨설팅] EFK Stack 소개와 설치 방법[오픈소스컨설팅] EFK Stack 소개와 설치 방법
[오픈소스컨설팅] EFK Stack 소개와 설치 방법
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
HTTP Request Smuggling via higher HTTP versions
HTTP Request Smuggling via higher HTTP versionsHTTP Request Smuggling via higher HTTP versions
HTTP Request Smuggling via higher HTTP versions
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
 
Vue.js
Vue.jsVue.js
Vue.js
 
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
 
[수정본] 우아한 객체지향
[수정본] 우아한 객체지향[수정본] 우아한 객체지향
[수정본] 우아한 객체지향
 
〈야생의 땅: 듀랑고〉 서버 아키텍처 Vol. 3
〈야생의 땅: 듀랑고〉 서버 아키텍처 Vol. 3〈야생의 땅: 듀랑고〉 서버 아키텍처 Vol. 3
〈야생의 땅: 듀랑고〉 서버 아키텍처 Vol. 3
 
Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)
 
[OPD 2019] Attacking JWT tokens
[OPD 2019] Attacking JWT tokens[OPD 2019] Attacking JWT tokens
[OPD 2019] Attacking JWT tokens
 
F5 ASM v12 DDoS best practices
F5 ASM v12 DDoS best practices F5 ASM v12 DDoS best practices
F5 ASM v12 DDoS best practices
 
mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교
 
Pentesting Rest API's by :- Gaurang Bhatnagar
Pentesting Rest API's by :- Gaurang BhatnagarPentesting Rest API's by :- Gaurang Bhatnagar
Pentesting Rest API's by :- Gaurang Bhatnagar
 
FIFA 온라인 3의 MongoDB 사용기
FIFA 온라인 3의 MongoDB 사용기FIFA 온라인 3의 MongoDB 사용기
FIFA 온라인 3의 MongoDB 사용기
 
쿠키런 1년, 서버개발 분투기
쿠키런 1년, 서버개발 분투기쿠키런 1년, 서버개발 분투기
쿠키런 1년, 서버개발 분투기
 
4. 대용량 아키텍쳐 설계 패턴
4. 대용량 아키텍쳐 설계 패턴4. 대용량 아키텍쳐 설계 패턴
4. 대용량 아키텍쳐 설계 패턴
 
A story of the passive aggressive sysadmin of AEM
A story of the passive aggressive sysadmin of AEMA story of the passive aggressive sysadmin of AEM
A story of the passive aggressive sysadmin of AEM
 
대용량 분산 아키텍쳐 설계 #5. rest
대용량 분산 아키텍쳐 설계 #5. rest대용량 분산 아키텍쳐 설계 #5. rest
대용량 분산 아키텍쳐 설계 #5. rest
 
CNIT 129S: Securing Web Applications Ch 1-2
CNIT 129S: Securing Web Applications Ch 1-2CNIT 129S: Securing Web Applications Ch 1-2
CNIT 129S: Securing Web Applications Ch 1-2
 

Similar to Hibernate ORM: Tips, Tricks, and Performance Techniques

hibernateormfeatures-140223193044-phpapp02.pdf
hibernateormfeatures-140223193044-phpapp02.pdfhibernateormfeatures-140223193044-phpapp02.pdf
hibernateormfeatures-140223193044-phpapp02.pdf
Patiento Del Mar
 
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
Not Just ORM: Powerful Hibernate ORM Features and CapabilitiesNot Just ORM: Powerful Hibernate ORM Features and Capabilities
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
Brett Meyer
 
How to Write the Fastest JSON Parser/Writer in the World
How to Write the Fastest JSON Parser/Writer in the WorldHow to Write the Fastest JSON Parser/Writer in the World
How to Write the Fastest JSON Parser/Writer in the World
Milo Yip
 
Yapc10 Cdt World Domination
Yapc10   Cdt World DominationYapc10   Cdt World Domination
Yapc10 Cdt World DominationcPanel
 
Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)
Ryan Cuprak
 
Performance and Abstractions
Performance and AbstractionsPerformance and Abstractions
Performance and Abstractions
Metosin Oy
 
Black Hat: XML Out-Of-Band Data Retrieval
Black Hat: XML Out-Of-Band Data RetrievalBlack Hat: XML Out-Of-Band Data Retrieval
Black Hat: XML Out-Of-Band Data Retrieval
qqlan
 
Alfresco Business Reporting - Tech Talk Live 20130501
Alfresco Business Reporting - Tech Talk Live 20130501Alfresco Business Reporting - Tech Talk Live 20130501
Alfresco Business Reporting - Tech Talk Live 20130501
Tjarda Peelen
 
ITB2017 - Slaying the ORM dragons with cborm
ITB2017 - Slaying the ORM dragons with cbormITB2017 - Slaying the ORM dragons with cborm
ITB2017 - Slaying the ORM dragons with cborm
Ortus Solutions, Corp
 
Tuenti Release Workflow
Tuenti Release WorkflowTuenti Release Workflow
Tuenti Release Workflow
Tuenti
 
Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Codersebbe
 
Introduction_to_Python.pptx
Introduction_to_Python.pptxIntroduction_to_Python.pptx
Introduction_to_Python.pptx
RahulChaudhary51756
 
What-is-Laravel-23-August-2017.pptx
What-is-Laravel-23-August-2017.pptxWhat-is-Laravel-23-August-2017.pptx
What-is-Laravel-23-August-2017.pptx
AbhijeetKumar456867
 
[Russia] Bugs -> max, time &lt;= T
[Russia] Bugs -> max, time &lt;= T[Russia] Bugs -> max, time &lt;= T
[Russia] Bugs -> max, time &lt;= T
OWASP EEE
 
Introduction of vertical crawler
Introduction of vertical crawlerIntroduction of vertical crawler
Introduction of vertical crawler
Jinglun Li
 
Find maximum bugs in limited time
Find maximum bugs in limited timeFind maximum bugs in limited time
Find maximum bugs in limited time
beched
 
Ruby and Distributed Storage Systems
Ruby and Distributed Storage SystemsRuby and Distributed Storage Systems
Ruby and Distributed Storage Systems
SATOSHI TAGOMORI
 
Killing Shark-Riding Dinosaurs with ORM
Killing Shark-Riding Dinosaurs with ORMKilling Shark-Riding Dinosaurs with ORM
Killing Shark-Riding Dinosaurs with ORM
Ortus Solutions, Corp
 
Apache Solr - Enterprise search platform
Apache Solr - Enterprise search platformApache Solr - Enterprise search platform
Apache Solr - Enterprise search platform
Tommaso Teofili
 
Scaling with swagger
Scaling with swaggerScaling with swagger
Scaling with swagger
Tony Tam
 

Similar to Hibernate ORM: Tips, Tricks, and Performance Techniques (20)

hibernateormfeatures-140223193044-phpapp02.pdf
hibernateormfeatures-140223193044-phpapp02.pdfhibernateormfeatures-140223193044-phpapp02.pdf
hibernateormfeatures-140223193044-phpapp02.pdf
 
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
Not Just ORM: Powerful Hibernate ORM Features and CapabilitiesNot Just ORM: Powerful Hibernate ORM Features and Capabilities
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
 
How to Write the Fastest JSON Parser/Writer in the World
How to Write the Fastest JSON Parser/Writer in the WorldHow to Write the Fastest JSON Parser/Writer in the World
How to Write the Fastest JSON Parser/Writer in the World
 
Yapc10 Cdt World Domination
Yapc10   Cdt World DominationYapc10   Cdt World Domination
Yapc10 Cdt World Domination
 
Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)
 
Performance and Abstractions
Performance and AbstractionsPerformance and Abstractions
Performance and Abstractions
 
Black Hat: XML Out-Of-Band Data Retrieval
Black Hat: XML Out-Of-Band Data RetrievalBlack Hat: XML Out-Of-Band Data Retrieval
Black Hat: XML Out-Of-Band Data Retrieval
 
Alfresco Business Reporting - Tech Talk Live 20130501
Alfresco Business Reporting - Tech Talk Live 20130501Alfresco Business Reporting - Tech Talk Live 20130501
Alfresco Business Reporting - Tech Talk Live 20130501
 
ITB2017 - Slaying the ORM dragons with cborm
ITB2017 - Slaying the ORM dragons with cbormITB2017 - Slaying the ORM dragons with cborm
ITB2017 - Slaying the ORM dragons with cborm
 
Tuenti Release Workflow
Tuenti Release WorkflowTuenti Release Workflow
Tuenti Release Workflow
 
Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Code
 
Introduction_to_Python.pptx
Introduction_to_Python.pptxIntroduction_to_Python.pptx
Introduction_to_Python.pptx
 
What-is-Laravel-23-August-2017.pptx
What-is-Laravel-23-August-2017.pptxWhat-is-Laravel-23-August-2017.pptx
What-is-Laravel-23-August-2017.pptx
 
[Russia] Bugs -> max, time &lt;= T
[Russia] Bugs -> max, time &lt;= T[Russia] Bugs -> max, time &lt;= T
[Russia] Bugs -> max, time &lt;= T
 
Introduction of vertical crawler
Introduction of vertical crawlerIntroduction of vertical crawler
Introduction of vertical crawler
 
Find maximum bugs in limited time
Find maximum bugs in limited timeFind maximum bugs in limited time
Find maximum bugs in limited time
 
Ruby and Distributed Storage Systems
Ruby and Distributed Storage SystemsRuby and Distributed Storage Systems
Ruby and Distributed Storage Systems
 
Killing Shark-Riding Dinosaurs with ORM
Killing Shark-Riding Dinosaurs with ORMKilling Shark-Riding Dinosaurs with ORM
Killing Shark-Riding Dinosaurs with ORM
 
Apache Solr - Enterprise search platform
Apache Solr - Enterprise search platformApache Solr - Enterprise search platform
Apache Solr - Enterprise search platform
 
Scaling with swagger
Scaling with swaggerScaling with swagger
Scaling with swagger
 

Recently uploaded

How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 

Recently uploaded (20)

How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 

Hibernate ORM: Tips, Tricks, and Performance Techniques

  • 1.
  • 2. Hibernate ORM: Tips, Tricks, and Performance Techniques Brett Meyer Senior Software Engineer Hibernate ORM, Red Hat
  • 3. Brett Meyer • Hibernate ORM – ORM 4 & 5 development – Hibernate OSGi – Developer community engagement – Red Hat enterprise support, Hibernate engineering lead • Other contributions – Apache Camel – Infinispan • Contact me – @brettemeyer or +brettmeyer – Freenode #hibernate or #hibernate-dev (brmeyer)
  • 5. ORM? JPA? • ORM: Object/Relational Mapping – Persistence: Data objects outlive the JVM app – Maps Java POJOs to relational databases – Supports OO concepts: inheritance, object identity, etc. – Navigate data by walking the object graph, not the explicit relational model • JPA: Java Persistence API • Hibernate ORM provides its own native API, in addition to full JPA support • Annotations and XML
  • 6. Overview • • • • • • • • Fetching Strategies 2nd Level Entity Cache Query Cache Cache Management Bytecode Enhancement Hibernate Search Misc. Tips Q&A
  • 7. Caveats • No “one strategy to rule them all” • Varies greatly between apps • Important to understand concepts, then apply as necessary • Does not replace database tuning!
  • 8. First, the antithesis: public User get(String username) { final Session session = openSession(); session.getTransaction().begin(); final User user = (User) session.get( User.class, username ); session.getTransaction().commit(); return user; } public boolean login(String username) { return get(username) != null; } Clean? Yes. But...
  • 9. EAGER Demo • Prototypes start “simple” – EAGER – No caching – Overuse of the kitchen sink • DAO looks clean • Then you see the SQL logs
  • 11. Fetching Strategies • By far, the most frequent mistake • Also the most costly • 2 concepts: – WHEN (fetch timing) – HOW (fetch style)
  • 13. Fetch Timing: EAGER • • • • Immediate Can be convenient (in some ways) Significantly increases payload Enormous amount of unnecessary fetches for deep association tree
  • 14. Fetch Timing: LAZY • Fetched when first accessed • Collections – LAZY by default – Utilizes Hibernate's internal concept of “persistent collections” – DEMO • Single attribute (basic) – Requires bytecode enhancement – Not typically used nor beneficial
  • 15. Fetch Timing: LAZY (cont'd) • Single (ToOne) associations – Fetched when accessed – Proxy • Default • Fetched when accessed (except ID) • Handled internally by Hibernate – No-proxy • Fetched when accessed (including ID) • No visible proxy • Requires buildtime bytecode enhancement
  • 16. Fetch Timing: EXTRA LAZY • • • • Collections only Fetch individual elements as accessed Does not fetch entire collection DEMO
  • 18. Fetch Style: JOIN • Join fetch (left/outer join) • Great for ToOne associations • Multiple collection joins – Possible for non-bags – Warning: Cartesian product! SELECT is normally faster • DEMO
  • 19. Fetch Style: SELECT • Follow-up selects • Default style for collections (avoids cartesian products) • Can result in 1+N selects (fetch per collection entry) • DEMO
  • 20. Fetch Style: BATCH • Fetches multiple entries when one is accessed • Configurable on both class and collection levels (“batch-size”) • Simple select and list of keys • Multiple algorithms (new as of 4.2) • Determines # of entries to fetch, based on # of provided keys
  • 21. Fetch Style: BATCH (cont'd) • Legacy: pre-determined sizes, rounded down – batch-size==25, 24 elements in collection – Fetches -> 12, 10, 2 • Padded: same as Legacy, size rounded up • Dynamic: builds SQL for the # of keys, limited by “batch-size” • DEMO
  • 22. Fetch Style: SUBSELECT • Follow-up select • Fetches all collection entries when accessed for the 1st time • Original root entry select used as subselect • Performance depends on the DB itself • DEMO
  • 23. Fetch Style: PROFILE • named profile defining fetch styles • “activated” through the Session
  • 24. @Entity @FetchProfile(name = "customer-with-orders", fetchOverrides = { @FetchProfile.FetchOverride(entity = Customer.class, association = "orders", mode = FetchMode.JOIN) }) public class Customer { ... @OneToMany private Set<Order> orders; ... } Session session = ...; session.enableFetchProfile( "customer-with-orders" ); Customer customer = (Customer) session.get( Customer.class, customerId );
  • 25. Fetch Style Tips • Best to leave defaults in mappings • Define the style at the query level • Granular control
  • 27. 2LC • differs from the 1st level (Session) • SessionFactory level (JVM) • can scale horizontally on commodity hardware (clustered) • multiple providers • currently focus on Infinispan (JBoss) & EHCache (Terracotta)
  • 28. 2LC (cont'd) • disabled by default – can enable globally (not recommended) – enable for individual entities and collections – configurable at the Session level w/ CacheMode • cache all properties (default) or only non-lazy
  • 29. 2LC (cont'd) • Since JVM-level, concurrency is an issue • Concurrency strategies – Read only: simplest and optimal – Read-write • Supports updates • Should not use for serializable transaction isolation – Nonstrict-read-write • If updates are occasional and unlikely to collide • No strict transaction isolation – Transactional: • Fully transactional cache providers (ie, Infinispan and EHCache) • JTA required
  • 32. Query Cache • Caches query result sets • Repetitive queries with identical params • Different from an entity cache – Does not maintain entity state – Holds on to sets of identifiers • If used, best in conjunction with 2LC
  • 33. Query Cache (cont'd) • Disabled by default • Many applications do not gain anything • Queries invalidated upon relevant updates • Increases overhead by some: tracks when to invalidate based on commits • DEMO
  • 35. Cache Management • Entities stored in Session cache when saved, updated, or retrieved • Session#flush syncs all cached with DB – Minimize usage • Manage memory: – Session#evict(entity) when no longer needed – Session#clear for all – Important for large dataset handling • Same for 2LC, but methods on SessionFactory#getCache
  • 37. Bytecode Enhancement • Not just for no-proxy, ToOne laziness • Reduced load on PersistenceContext – EntityEntry • Internally provides state & Session association • “Heavy” operation and typically a hotspot (multiple Maps) – ManagedEntity • Reduced memory and CPU loads • Entities maintain their own state with bytecode enhancement • (ManagedEntity)entity.$$_hibernate_getEntityEntry(); – 3 ways: • Entity implements ManagedEntity and maintains the association • Buildtime instrumentation (Ant and recently Gradle/Maven) • Runtime instrumentation
  • 38. Bytecode (cont'd) • dirtiness checking – Legacy: “dirtiness” determined by deep comparison of entity state – Enhancement: entity tracks its own dirtiness – Simply check the flag (no deep comparison) – Already mentioned… • Minimize amount of flushes to begin with • Minimize the # of entities in the cache -- evict when possible • Many additional bytecode improvements planned
  • 40. Hibernate Search • Full-text search on the DB – Bad performance – CPU/IO overhead • Offload full-text queries to Hibernate Search engine – Fully indexed – Horizontally scalable • Based on Apache Lucene
  • 41. Hibernate Search (cont'd) • Annotate entities with @Indexed • Annotate properties with @Field – Index the text: index=Index.YES – “Analyze” the text: analyze=Analyze.YES • • • • Lucene analyzer Chunks sentences into words Lowercase all of them Exclude common words (“a”, “the”) • Combo of indexing and analysis == performant full-text searches!
  • 43. Misc. Tips • Easy to overlook unintended fetches – Ex: Fully implemented toString with all associations (fetches everything simply for logging) • Use @Immutable when possible – Excludes entity from dirtiness checks – Other internal optimizations
  • 44. Misc. Tips (cont'd) • Use Bag or List for inverse collections, not Set – Collection#add & #addAll always return true (don't need to check for pre-existing values) – I.e., can add a value without fetching the collection Parent p = (Parent) session.load(Parent.class, id); Child c = new Child(); c.setParent(p); p.addChild(c); ... // does *not* fetch the collection p.getChildren().add(c);
  • 45. Misc. Tips (cont'd) • One-shot delete (non-inverse collections) – Scenario: 20 elements, need to delete 18 & add 3 – Default: Hibernate would delete the 18 one-byone, then add the 3 – Instead: • Discard the entire collection (deletes all elements) • Save a new collection with 5 elements • 1 bulk delete SQL and 5 inserts – Important concept for large amounts of data