SlideShare a Scribd company logo
No more than a few
milliseconds
Behind JPA and SQL
Query Optimizations
Gleydson Lima
gleydson@esig.com.br
https://www.linkedin.com/in/gleydsonlima
Agenda
• What is Fast?
• Common problems with JPA/Hibernate
• JPA/Hibernate Cache Levels
• Indexes
• Query Explain
• App Example
• Real App Examples
What is fast for the user?
Everything you do not realize loading
and feels instantaneous or close to it.
N + 1 SELECT Problem
● Main cases:
○ ManyToOne Associations
○ OneToOne Associations
○ OneToMany Associations
ManyToOne relationship
Example
N + 1 SELECT???
1? 2? Both?
1
2
Demo application
https://github.com/gleydsonlima/jpa-and-query-optimizer
Answer
● findAll: N + 1 select happened in this case.
The reason is that JPQL by default does not
consider the fetch strategy.
● findById: In this case, fetch EAGER is
considered to load the entity and its
associations with just ONE select.
Example
Demo application
N + 1 SELECT for OneToMany
Use Join Fetch
Only one collection per query.
Performance Tips
- Use EAGER in main association relationships;
- Use LAZY in ManyToOne less used for exhibition;
- Pay attention in your console with show_sql =
true. Be careful with too many selects.
- JQL query does not use FetchType definition!!!
Demo application
JPA Projection
Hibernate: select aluno0_.nome as col_0_0_, curso1_.id as
col_1_0_, curso1_.id as id1_1_, curso1_.nome as nome2_1_ from
opt.aluno aluno0_ left outer join opt.curso curso1_ on
aluno0_.curso_id=curso1_.id where aluno0_.nome like ? limit ?
offset ?
Demo application
Query Execution - PostgreSQL
The Explain Command
PostgreSQL devises a query plan for each query it receives.
Choosing the right plan to match the query structure and the properties of the data is absolutely
critical for good performance, so the system includes a complex planner that tries to choose good
plans.
You can use the EXPLAIN command to see what query plan the planner creates for any query
Explain - The simplest example
startup cost - in
general, for
sorting.
complete
phase cost
number of
rows
fetched
bytes
recovered.
The size of
information
SEQ_SCAN
Index Scan
Read the index tree and gets the
heap blocks pointed by the
index.
The
index_only_scan
Read the index tree and returns
the data without acessing the
heap page.
Bitmap_index/heap
scan
read the index sequentially generating
a bitmap used to recheck on heap
pages.
Index B-Tree
Very Important!!
Hibernate table creation does not create INDEX for
Foreign Keys!!!
Example in Demo Application
Two schemas
nopt: no index
Opt: with index
Case 01
"Nested Loop (cost=0.29..3821.09 rows=10
width=65)"
"Hash Join (cost=7.21..23.64 rows=10 width=57)"
Case 02
"Sort (cost=736.07..736.08 rows=2
width=520)"
"Sort (cost=704.07..704.08 rows=2
width=520)"
Case 02
There is no filter.
The couting function, in
this case, requires go
through all table.
The planner choose SEQ
SCAN even if you have
indexes.
Case 03
"Sort (cost=42790786.05..42790786.06
rows=2 width=520)"
"Sort (cost=91154.05..91154.06 rows=2
width=520)"
469x more computation units.
Case 04
"HashAggregate (cost=4588.41..4588.44
rows=3 width=12)"
"HashAggregate (cost=4144.45..4144.48
rows=3 width=12)"
Case 05
"Nested Loop (cost=535.00..4339.55
rows=500 width=531)"
"Nested Loop (cost=523.17..1817.23
rows=498 width=531)"
Example in Real ESIG Applications
(internal use only)
Tips
• Always use index for relevant foreign
keys
• Use native query for complex query.
• Explain your query
• Execute your query in real environment.
The average time must be less than
500ms!
• Create multi-column index for relevant
filters.
• Be careful: index uses disk space!
Future talks (Suggestion)
Join Operations
Nested Loops
Joins two tables by fetching the result from one table and querying the other table for each row from the first.
Hash Join / Hash
The hash join loads the candidate records from one side of the join into a hash table (marked with Hash in the plan) which
is then probed for each record from the other side of the join.
Merge Join
The (sort) merge join combines two sorted lists like a zipper. Both sides of the join must be presorted
Sorting and Grouping
Sort / Sort Key
Sorts the set on the columns mentioned in Sort Key. The Sortoperation needs large amounts of memory to materialize
the intermediate result (not pipelined).
GroupAggregate
Aggregates a presorted set according to the group by clause. This operation does not buffer large amounts of data
(pipelined).
HashAggregate
Uses a temporary hash table to group records. The HashAggregateoperation does not require a presorted data set, instead
it uses large amounts of memory to materialize the intermediate result (not pipelined). The output is not ordered in any
meaningful way.
Thanks!
+55 84 3034-9310 : : esig.com.br

More Related Content

What's hot

HEPData
HEPDataHEPData
Clustering: A Scikit Learn Tutorial
Clustering: A Scikit Learn TutorialClustering: A Scikit Learn Tutorial
Clustering: A Scikit Learn Tutorial
Damian R. Mingle, MBA
 
HEPData Open Repositories 2016 Talk
HEPData Open Repositories 2016 TalkHEPData Open Repositories 2016 Talk
HEPData Open Repositories 2016 Talk
Eamonn Maguire
 
Dev Games!
Dev Games!Dev Games!
Dev Games!
Adam Haley
 
3.2 stacks and arrays
3.2   stacks and arrays3.2   stacks and arrays
3.2 stacks and arraysallenbailey
 
Reproducible, Open Data Science in the Life Sciences
Reproducible, Open  Data Science in the  Life SciencesReproducible, Open  Data Science in the  Life Sciences
Reproducible, Open Data Science in the Life Sciences
Eamonn Maguire
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
Edureka!
 
Java - Collections
Java - CollectionsJava - Collections
Java - Collections
Amith jayasekara
 
Hashing and Hashtable, application of hashing, advantages of hashing, disadva...
Hashing and Hashtable, application of hashing, advantages of hashing, disadva...Hashing and Hashtable, application of hashing, advantages of hashing, disadva...
Hashing and Hashtable, application of hashing, advantages of hashing, disadva...
NaveenPeter8
 
Data structure lecture 2
Data structure lecture 2Data structure lecture 2
Data structure lecture 2
Abbott
 
A Survey on Improve Efficiency And Scability vertical mining using Agriculter...
A Survey on Improve Efficiency And Scability vertical mining using Agriculter...A Survey on Improve Efficiency And Scability vertical mining using Agriculter...
A Survey on Improve Efficiency And Scability vertical mining using Agriculter...
Editor IJMTER
 
Basic of Data Structure - Data Structure - Notes
Basic of Data Structure - Data Structure - NotesBasic of Data Structure - Data Structure - Notes
Basic of Data Structure - Data Structure - Notes
Omprakash Chauhan
 
Quick dive to pandas
Quick dive to pandasQuick dive to pandas
Quick dive to pandas
Robin Kiplangat
 
F# array searching
F#  array searchingF#  array searching
F# array searching
DrRajeshreeKhande
 
Advanced data access with Dapper
Advanced data access with DapperAdvanced data access with Dapper
Advanced data access with Dapper
David Paquette
 
Rijpma's Catasto meets SPARQL dhb2017_workshop
Rijpma's Catasto meets SPARQL dhb2017_workshopRijpma's Catasto meets SPARQL dhb2017_workshop
Rijpma's Catasto meets SPARQL dhb2017_workshop
Richard Zijdeman
 
Bloom filter
Bloom filterBloom filter
Bloom filter
Hamid Feizabadi
 
Intro to plyr for Davis R Users' Group, by Steve Culman
Intro to plyr for Davis R Users' Group, by Steve CulmanIntro to plyr for Davis R Users' Group, by Steve Culman
Intro to plyr for Davis R Users' Group, by Steve CulmanNoam Ross
 
Arrays
ArraysArrays

What's hot (20)

HEPData
HEPDataHEPData
HEPData
 
Clustering: A Scikit Learn Tutorial
Clustering: A Scikit Learn TutorialClustering: A Scikit Learn Tutorial
Clustering: A Scikit Learn Tutorial
 
HEPData Open Repositories 2016 Talk
HEPData Open Repositories 2016 TalkHEPData Open Repositories 2016 Talk
HEPData Open Repositories 2016 Talk
 
Dev Games!
Dev Games!Dev Games!
Dev Games!
 
3.2 stacks and arrays
3.2   stacks and arrays3.2   stacks and arrays
3.2 stacks and arrays
 
Amazon elastic map reduce
Amazon elastic map reduceAmazon elastic map reduce
Amazon elastic map reduce
 
Reproducible, Open Data Science in the Life Sciences
Reproducible, Open  Data Science in the  Life SciencesReproducible, Open  Data Science in the  Life Sciences
Reproducible, Open Data Science in the Life Sciences
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
 
Java - Collections
Java - CollectionsJava - Collections
Java - Collections
 
Hashing and Hashtable, application of hashing, advantages of hashing, disadva...
Hashing and Hashtable, application of hashing, advantages of hashing, disadva...Hashing and Hashtable, application of hashing, advantages of hashing, disadva...
Hashing and Hashtable, application of hashing, advantages of hashing, disadva...
 
Data structure lecture 2
Data structure lecture 2Data structure lecture 2
Data structure lecture 2
 
A Survey on Improve Efficiency And Scability vertical mining using Agriculter...
A Survey on Improve Efficiency And Scability vertical mining using Agriculter...A Survey on Improve Efficiency And Scability vertical mining using Agriculter...
A Survey on Improve Efficiency And Scability vertical mining using Agriculter...
 
Basic of Data Structure - Data Structure - Notes
Basic of Data Structure - Data Structure - NotesBasic of Data Structure - Data Structure - Notes
Basic of Data Structure - Data Structure - Notes
 
Quick dive to pandas
Quick dive to pandasQuick dive to pandas
Quick dive to pandas
 
F# array searching
F#  array searchingF#  array searching
F# array searching
 
Advanced data access with Dapper
Advanced data access with DapperAdvanced data access with Dapper
Advanced data access with Dapper
 
Rijpma's Catasto meets SPARQL dhb2017_workshop
Rijpma's Catasto meets SPARQL dhb2017_workshopRijpma's Catasto meets SPARQL dhb2017_workshop
Rijpma's Catasto meets SPARQL dhb2017_workshop
 
Bloom filter
Bloom filterBloom filter
Bloom filter
 
Intro to plyr for Davis R Users' Group, by Steve Culman
Intro to plyr for Davis R Users' Group, by Steve CulmanIntro to plyr for Davis R Users' Group, by Steve Culman
Intro to plyr for Davis R Users' Group, by Steve Culman
 
Arrays
ArraysArrays
Arrays
 

Similar to Tech Talk - JPA and Query Optimization - publish

Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09
guest9d79e073
 
Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09
Mark Ginnebaugh
 
Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008paulguerin
 
PostgreSQL 9.6 Performance-Scalability Improvements
PostgreSQL 9.6 Performance-Scalability ImprovementsPostgreSQL 9.6 Performance-Scalability Improvements
PostgreSQL 9.6 Performance-Scalability Improvements
PGConf APAC
 
PostgreSQL Table Partitioning / Sharding
PostgreSQL Table Partitioning / ShardingPostgreSQL Table Partitioning / Sharding
PostgreSQL Table Partitioning / Sharding
Amir Reza Hashemi
 
Data structure and algorithm.
Data structure and algorithm. Data structure and algorithm.
Data structure and algorithm.
Abdul salam
 
Analysis Services Best Practices From Large Deployments
Analysis Services   Best Practices From Large DeploymentsAnalysis Services   Best Practices From Large Deployments
Analysis Services Best Practices From Large Deploymentsrsnarayanan
 
Instant DBMS Homework Help
Instant DBMS Homework HelpInstant DBMS Homework Help
Instant DBMS Homework Help
Database Homework Help
 
To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hib...
To Study The Tips Tricks  Guidelines Related To Performance Tuning For  N Hib...To Study The Tips Tricks  Guidelines Related To Performance Tuning For  N Hib...
To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hib...
Shahzad
 
My SQL Skills Killed the Server
My SQL Skills Killed the ServerMy SQL Skills Killed the Server
My SQL Skills Killed the Server
devObjective
 
PostgreSQL High_Performance_Cheatsheet
PostgreSQL High_Performance_CheatsheetPostgreSQL High_Performance_Cheatsheet
PostgreSQL High_Performance_Cheatsheet
Lucian Oprea
 
Database Performance Tuning
Database Performance Tuning Database Performance Tuning
Database Performance Tuning
Arno Huetter
 
Query optimization
Query optimizationQuery optimization
Query optimization
Pooja Dixit
 
Things you can find in the plan cache
Things you can find in the plan cacheThings you can find in the plan cache
Things you can find in the plan cachesqlserver.co.il
 
123448572 all-in-one-informatica
123448572 all-in-one-informatica123448572 all-in-one-informatica
123448572 all-in-one-informatica
homeworkping9
 
22827361 ab initio-fa-qs
22827361 ab initio-fa-qs22827361 ab initio-fa-qs
22827361 ab initio-fa-qsCapgemini
 
Intro to SnappyData Webinar
Intro to SnappyData WebinarIntro to SnappyData Webinar
Intro to SnappyData Webinar
SnappyData
 
15 Ways to Kill Your Mysql Application Performance
15 Ways to Kill Your Mysql Application Performance15 Ways to Kill Your Mysql Application Performance
15 Ways to Kill Your Mysql Application Performance
guest9912e5
 

Similar to Tech Talk - JPA and Query Optimization - publish (20)

Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09
 
Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09
 
Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008
 
PostgreSQL 9.6 Performance-Scalability Improvements
PostgreSQL 9.6 Performance-Scalability ImprovementsPostgreSQL 9.6 Performance-Scalability Improvements
PostgreSQL 9.6 Performance-Scalability Improvements
 
PostgreSQL Table Partitioning / Sharding
PostgreSQL Table Partitioning / ShardingPostgreSQL Table Partitioning / Sharding
PostgreSQL Table Partitioning / Sharding
 
Data structure and algorithm.
Data structure and algorithm. Data structure and algorithm.
Data structure and algorithm.
 
Analysis Services Best Practices From Large Deployments
Analysis Services   Best Practices From Large DeploymentsAnalysis Services   Best Practices From Large Deployments
Analysis Services Best Practices From Large Deployments
 
Instant DBMS Homework Help
Instant DBMS Homework HelpInstant DBMS Homework Help
Instant DBMS Homework Help
 
To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hib...
To Study The Tips Tricks  Guidelines Related To Performance Tuning For  N Hib...To Study The Tips Tricks  Guidelines Related To Performance Tuning For  N Hib...
To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hib...
 
My SQL Skills Killed the Server
My SQL Skills Killed the ServerMy SQL Skills Killed the Server
My SQL Skills Killed the Server
 
Sql killedserver
Sql killedserverSql killedserver
Sql killedserver
 
PostgreSQL High_Performance_Cheatsheet
PostgreSQL High_Performance_CheatsheetPostgreSQL High_Performance_Cheatsheet
PostgreSQL High_Performance_Cheatsheet
 
Database Performance Tuning
Database Performance Tuning Database Performance Tuning
Database Performance Tuning
 
Query optimization
Query optimizationQuery optimization
Query optimization
 
Query processing System
Query processing SystemQuery processing System
Query processing System
 
Things you can find in the plan cache
Things you can find in the plan cacheThings you can find in the plan cache
Things you can find in the plan cache
 
123448572 all-in-one-informatica
123448572 all-in-one-informatica123448572 all-in-one-informatica
123448572 all-in-one-informatica
 
22827361 ab initio-fa-qs
22827361 ab initio-fa-qs22827361 ab initio-fa-qs
22827361 ab initio-fa-qs
 
Intro to SnappyData Webinar
Intro to SnappyData WebinarIntro to SnappyData Webinar
Intro to SnappyData Webinar
 
15 Ways to Kill Your Mysql Application Performance
15 Ways to Kill Your Mysql Application Performance15 Ways to Kill Your Mysql Application Performance
15 Ways to Kill Your Mysql Application Performance
 

Recently uploaded

Game Development with Unity3D (Game Development lecture 3)
Game Development  with Unity3D (Game Development lecture 3)Game Development  with Unity3D (Game Development lecture 3)
Game Development with Unity3D (Game Development lecture 3)
abdulrafaychaudhry
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptxText-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
ShamsuddeenMuhammadA
 
AI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website CreatorAI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website Creator
Google
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 

Recently uploaded (20)

Game Development with Unity3D (Game Development lecture 3)
Game Development  with Unity3D (Game Development lecture 3)Game Development  with Unity3D (Game Development lecture 3)
Game Development with Unity3D (Game Development lecture 3)
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptxText-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
 
AI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website CreatorAI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website Creator
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 

Tech Talk - JPA and Query Optimization - publish

  • 1. No more than a few milliseconds Behind JPA and SQL Query Optimizations Gleydson Lima gleydson@esig.com.br https://www.linkedin.com/in/gleydsonlima
  • 2. Agenda • What is Fast? • Common problems with JPA/Hibernate • JPA/Hibernate Cache Levels • Indexes • Query Explain • App Example • Real App Examples
  • 3. What is fast for the user? Everything you do not realize loading and feels instantaneous or close to it.
  • 4. N + 1 SELECT Problem ● Main cases: ○ ManyToOne Associations ○ OneToOne Associations ○ OneToMany Associations
  • 7. N + 1 SELECT??? 1? 2? Both? 1 2
  • 9. Answer ● findAll: N + 1 select happened in this case. The reason is that JPQL by default does not consider the fetch strategy. ● findById: In this case, fetch EAGER is considered to load the entity and its associations with just ONE select.
  • 12. N + 1 SELECT for OneToMany Use Join Fetch Only one collection per query.
  • 13. Performance Tips - Use EAGER in main association relationships; - Use LAZY in ManyToOne less used for exhibition; - Pay attention in your console with show_sql = true. Be careful with too many selects. - JQL query does not use FetchType definition!!!
  • 14.
  • 15.
  • 17. JPA Projection Hibernate: select aluno0_.nome as col_0_0_, curso1_.id as col_1_0_, curso1_.id as id1_1_, curso1_.nome as nome2_1_ from opt.aluno aluno0_ left outer join opt.curso curso1_ on aluno0_.curso_id=curso1_.id where aluno0_.nome like ? limit ? offset ?
  • 19. Query Execution - PostgreSQL
  • 20. The Explain Command PostgreSQL devises a query plan for each query it receives. Choosing the right plan to match the query structure and the properties of the data is absolutely critical for good performance, so the system includes a complex planner that tries to choose good plans. You can use the EXPLAIN command to see what query plan the planner creates for any query
  • 21. Explain - The simplest example startup cost - in general, for sorting. complete phase cost number of rows fetched bytes recovered. The size of information
  • 23. Index Scan Read the index tree and gets the heap blocks pointed by the index.
  • 24. The index_only_scan Read the index tree and returns the data without acessing the heap page.
  • 25. Bitmap_index/heap scan read the index sequentially generating a bitmap used to recheck on heap pages.
  • 27.
  • 28.
  • 29. Very Important!! Hibernate table creation does not create INDEX for Foreign Keys!!!
  • 30. Example in Demo Application Two schemas nopt: no index Opt: with index
  • 31. Case 01 "Nested Loop (cost=0.29..3821.09 rows=10 width=65)" "Hash Join (cost=7.21..23.64 rows=10 width=57)"
  • 32. Case 02 "Sort (cost=736.07..736.08 rows=2 width=520)" "Sort (cost=704.07..704.08 rows=2 width=520)"
  • 33. Case 02 There is no filter. The couting function, in this case, requires go through all table. The planner choose SEQ SCAN even if you have indexes.
  • 34. Case 03 "Sort (cost=42790786.05..42790786.06 rows=2 width=520)" "Sort (cost=91154.05..91154.06 rows=2 width=520)" 469x more computation units.
  • 35. Case 04 "HashAggregate (cost=4588.41..4588.44 rows=3 width=12)" "HashAggregate (cost=4144.45..4144.48 rows=3 width=12)"
  • 36. Case 05 "Nested Loop (cost=535.00..4339.55 rows=500 width=531)" "Nested Loop (cost=523.17..1817.23 rows=498 width=531)"
  • 37. Example in Real ESIG Applications (internal use only)
  • 38. Tips • Always use index for relevant foreign keys • Use native query for complex query. • Explain your query • Execute your query in real environment. The average time must be less than 500ms! • Create multi-column index for relevant filters. • Be careful: index uses disk space!
  • 39. Future talks (Suggestion) Join Operations Nested Loops Joins two tables by fetching the result from one table and querying the other table for each row from the first. Hash Join / Hash The hash join loads the candidate records from one side of the join into a hash table (marked with Hash in the plan) which is then probed for each record from the other side of the join. Merge Join The (sort) merge join combines two sorted lists like a zipper. Both sides of the join must be presorted
  • 40. Sorting and Grouping Sort / Sort Key Sorts the set on the columns mentioned in Sort Key. The Sortoperation needs large amounts of memory to materialize the intermediate result (not pipelined). GroupAggregate Aggregates a presorted set according to the group by clause. This operation does not buffer large amounts of data (pipelined). HashAggregate Uses a temporary hash table to group records. The HashAggregateoperation does not require a presorted data set, instead it uses large amounts of memory to materialize the intermediate result (not pipelined). The output is not ordered in any meaningful way.
  • 42. +55 84 3034-9310 : : esig.com.br