SlideShare ist ein Scribd-Unternehmen logo
1 von 53
Performance Tuning
Sander Mak
Outline
 Optimization
 Lazy loading
 Examples ‘from the trenches’
   Search queries
   Large collections
   Batching
 Odds & Ends
Optimization
Hibernate Sucks!
      ... because it’s slow
Hibernate Sucks!
      ... because it’s slow
     ‘The problem is sort of cultural [..] developers
     use Hibernate because they are uncomfortable
     with SQL and with RDBMSes. You should be
     very comfortable with SQL and JDBC before you
     start using Hibernate - Hibernate builds on
     JDBC, it doesn’t replace it. That is the cost of
     extra abstraction [..] save yourself effort,
     pay attention to the database at all stages
     of development.
                               - Gavin King (creator)
Optimization is hard
 Performance blamed on?
   Framework <-> You
 How to optimize?
 When to optimize?
 Production vs. development
 Preserve correctness at all times
   Unit tests ok, but not enough
Optimization is hard
 Performance blamed on?
   Framework <-> You
 How to optimize?
 When to optimize?
 Production vs. development
 Preserve correctness at all times
   Unit tests ok, but not enough

  Premature optimization is the root of all evil
                                     - Donald Knuth
Optimization guidelines
 Always measure
   Establish baseline and measure improvement
   Be prepared to detect performance degradation!
 Favor obvious over obscure
   Even if latter performs better
 Know your RDBMS (hook up with a good DBA)
   Details do matter
   Database is not a dumb ‘bit-bucket’
Optimization guidelines
Measurement
 Ensure stable, production-like environment
 Measure time and space
   Time: isolate timings in different layers
   Space: more heap -> longer GC -> slower
 Try to measure in RDBMS as well
   Memory usage (hot cache or disk thrashing?)
   Query plans
 Make many measurements
Optimization guidelines
Measurement
 Ensure stable, production-like environment
 Measure time and space
   Time: isolate timings in different layers
   Space: more heap -> longer GC -> slower
 Try to measure in RDBMS as well
   Memory usage (hot cache or disk thrashing?)
   Query plans
 Make many measurements
    Remember: measurements are relative
Optimization guidelines
Practical
 ProïŹler on DAO/Session.query() methods
 VisualVM etc. for heap usage
   Also: JRockit Mission Control

 Hibernate JMX
  <property name="hibernate.generate_statistics">true
  </property>




 RDBMS monitoring tools
Optimization guidelines
Practical
 Example from BMG tuning session:
Analyzing Hibernate
Log SQL:   <property name="show_sql">true</property>
           <property name="format_sql">true</property>


Log4J conïŹguration:
  org.hibernate -> DEBUG
  org.hibernate.type -> FINE (see bound params)

Or use P6Spy to snoop on JDBC connection
Analyzing Hibernate
Log SQL:   <property name="show_sql">true</property>
           <property name="format_sql">true</property>


Log4J conïŹguration:
  org.hibernate -> DEBUG
  org.hibernate.type -> FINE (see bound params)

Or use P6Spy to snoop on JDBC connection
Analyzing Hibernate
Lazy loading
Lazy loading
One entity to rule them all                   Request

Mostly sane defaults:                                  1..1




@OneToOne,
@OneToMany,                                      User
@ManyToMany: LAZY                             1..*          *..1


@ManyToOne : EAGER
Due to JPA spec.              Authorization

                                                 *..1


                                Global               1..*          Company
                               Company
Lazy loading
                               Request
                                        1..1




                                  User

                               1..*          *..1




               Authorization

                                  *..1


                 Global               1..*          Company
                Company
LazyInitializationException
Lazy loading          N+1 Selects problem

Select list of N users      HQL: SELECT u FROM User

Authorizations necessary:   SQL 1 query:
                            SELECT * FROM User
  N select queries on         LEFT JOIN Company c
  Authorization executed!     WHERE u.worksForCompany =
                              c.id


Solution:
  FETCH JOINS
Lazy loading          N+1 Selects problem

Select list of N users      HQL: SELECT u FROM User

Authorizations necessary:   SQL N queries:
                            SELECT * FROM Authorization
  N select queries on         WHERE userId = N
  Authorization executed!

Solution:
  FETCH JOINS
Lazy loading          N+1 Selects problem

Select list of N users      HQL: SELECT u FROM User
                            JOIN FETCH u.authorizations
Authorizations necessary:
                            SQL 1 query:
  N select queries on       SELECT * FROM User
  Authorization executed!     LEFT JOIN Company c LEFT
                              OUTER JOIN Authorization
                              ON .. WHERE
Solution:                     u.worksForCompany = c.id

  FETCH JOINS
Lazy loading
Some guidelines
 Laziness by default = mostly good
 However, architectural impact:
   Session lifetime (‘OpenSessionInView’ pattern)
   Extended Persistence Context
   Proxy usage (runtime code generation)
 Eagerness can be forced with HQL/JPAQL/Criteria
 But eagerness cannot be revoked
   exception: Session.load()/EntityManager.getReference()
Search queries
Search queries




                   User

                1..*          *..1




Authorization

                   *..1


  Global               1..*          Company
 Company
Search queries
Obvious solution:

Too much information!
Use summary objects:



UserSummary = POJO
  not attached, only necessary ïŹelds (no relations)
Search queries
Obvious solution:

Too much information!
Use summary objects:



UserSummary = POJO
  not attached, only necessary ïŹelds (no relations)
  Or: drop down to JDBC to fetch id + ïŹelds
Search queries
Alternative:

Taking it further:




Pagination in queries, not in app. code
Extra count query may be necessary (totals)
         Ordering necessary for paging!
Search queries
          Subtle:
Alternative: effect of applying setMaxResults
          “The
           or setFirstResult to a query involving
         fetch joins over collections is undeïŹned”
Taking it further:
         Cause: the emitted join possibly returns
             several rows per entity. So LIMIT,
            rownums, TOP cannot be used!
          Instead Hibernate must fetch all rows
         WARNING: firstResult/maxResults specified with
Pagination in queries, not in app. code
                  collection fetch; applying in memory!


Extra count query may be necessary (totals)
         Ordering necessary for paging!
Large collections
Large collections
      Frontend:
       Request
     CompanyGroup
          1..*


                             Backend:
        Company
                            CompanyGroup
                                  1..*
                                             Meta-data


Company read-only entity,   CompanyInGroup
backed by expensive view          *..1




                               Company
Large collections
  Frontend:
   Request
 CompanyGroup
      1..*


                    Backend:
   Company
                    CompanyGroup
                         1..*
                                   Meta-data

                CompanyInGroup
                         *..1




                      Company
Large collections
  Frontend:
   Request
 CompanyGroup
      1..*


                    Backend:
   Company
                    CompanyGroup
                         1..*
                                   Meta-data

                CompanyInGroup
                         *..1




                      Company
Large collections
 Opening large groups sluggish
 Improved performance:

 Fetches many uninitialized collections in 1 query
 Also possible on entity:

                                                 Request
                                               CompanyGroup
                                                     1..*




                                                 Company
Large collections
 Opening large groups sluggish
 Improved performance:

 Fetches many uninitialized collections in 1 query
 Also possible on entity:

                                                    Request
                                                  CompanyGroup
                                                       1..*




                                                    Company
       Better solution in hindsight: fetch join
Large collections
 Saving large group slow: >15 sec.
 Problem: Hibernate inserts row by row
   Query creation overhead, network latency
 Solution: <property name="hibernate.jdbc.batch_size">100
              </property>


 Enables JDBC batched statements
 Caution: global property                                 Request
                                                        CompanyGroup

 Also: <property name="hibernate.order_inserts">true
                                                              1..*




        </property>                                         Company
        <property name="hibernate.order_updates">true
        </property>
Large collections
  Frontend:
   Request
 CompanyGroup
      1..*


                    Backend:
   Company
                    CompanyGroup
                         1..*
                                   Meta-data

                CompanyInGroup
                         *..1




                      Company
Large collections


                    Backend:

                    CompanyGroup
                         1..*
                                   Meta-data

                CompanyInGroup
                         *..1




                      Company
Large collections
Process   CreateGroup (Soap)   Business
Service                         Service

 CreateGroup took ~10 min. for 1000 companies
 @BatchSize on Company improved demarshalling
 JDBC batch_size property marginal improvement
 INFO: INSERT INTO CompanyInGroup VALUES (?,...,?)
 INFO: SELECT @identity
 INFO: INSERT INTO CompanyInGroup VALUES (?,...,?)
 INFO: SELECT @identity
 .. 1000 times                                       CompanyGroup
                                                           1..*
                                                                      Meta-data


 Insert/select interleaved: due to gen. id           CompanyInGroup
                                                           *..1




                                                        Company
Large collections
Process    CreateGroup (Soap)   Business
Service                          Service

 Solution: generate id in app. (not always feasible)
 Running in ~3 minutes with batched inserts
 Next problem: heap usage spiking
 Use StatelessSession
  ✩ Bypass ïŹrst-level cache
  ✩ No automatic dirty checking                     CompanyGroup

  ✩ Bypass Hibernate event model and interceptors         1..*
                                                                     Meta-data

  ✩ No cascading of operations                      CompanyInGroup
  ✩ Collections on entities are ignored                   *..1




                                                       Company
Large collections
Process   CreateGroup (Soap)   Business
Service                         Service

 Solution: generate id in app. (not always feasible)
 Running in ~3 minutes with batched inserts
 Next problem: heap usage spiking
 Use StatelessSession

                                              CompanyGroup
                                                    1..*
                                                               Meta-data

                                              CompanyInGroup
                                                    *..1




                                                 Company
Large collections
Process   CreateGroup (Soap)   Business
Service                         Service

 Now ~1 min., everybody happy!




                                          CompanyGroup
                                                1..*
                                                           Meta-data

                                          CompanyInGroup
                                                *..1




                                             Company
Large collections
Process   CreateGroup (Soap)   Business
Service                         Service

 Now ~1 min., everybody happy!


      Data loss detected!

                                          CompanyGroup
                                                1..*
                                                           Meta-data

                                          CompanyInGroup
                                                *..1




                                             Company
Large collections
Process   CreateGroup (Soap)   Business
Service                         Service   Data loss detected!

 StatelessSession and JDBC batch_size bug
 Only ‘full’ batches are performed!



 HHH-4042: Closed, won’t ïŹx :
                                                    CompanyGroup
                                                         1..*
                                                                    Meta-data

                                                   CompanyInGroup
                                                         *..1




                                                      Company
Odds & Ends
Query hints
Speed up read-only service calls:



Hibernate Query.setHint():




Also: never use 2nd level cache just ‘because we can’
Query hints
Speed up read-only service calls:



Hibernate Query.setHint():




Also: never use 2nd level cache just ‘because we can’
@org.hibernate.annotations.Entity(mutable = false)
Large updates
Naive approach:



Entities are not always necessary:



Changes are not reïŹ‚ected in persistence context
With optimistic concurrency: VERSIONED keyword
Large updates
Naive approach:



Entities are not always necessary:



Changes are not reïŹ‚ected in persistence context
With optimistic concurrency: VERSIONED keyword
       Consider use of stored procedures
Dynamic updates
@org.hibernate.annotations.Entity (dynamicInsert =
true, dynamicUpdate = true )

Only changed columns updated/inserted
BeneïŹcial for tables with many columns
Downsides
 Runtime SQL generation overhead
 No PreparedStatement (caching) used anymore
Cherish your database
Data and schema probably live longer than app.
Good indexes make a world of difference
Stored procedures etc. are not inherently evil
Do not let Hibernate dictate your schema
  Though sometimes you are forced

There are other solutions (there I said it)
Read the Endeavour JPA Guideline!
Questions

Weitere Àhnliche Inhalte

Was ist angesagt?

Patterns and Operational Insights from the First Users of Delta Lake
Patterns and Operational Insights from the First Users of Delta LakePatterns and Operational Insights from the First Users of Delta Lake
Patterns and Operational Insights from the First Users of Delta LakeDatabricks
 
Dr. Elephant for Monitoring and Tuning Apache Spark Jobs on Hadoop with Carl ...
Dr. Elephant for Monitoring and Tuning Apache Spark Jobs on Hadoop with Carl ...Dr. Elephant for Monitoring and Tuning Apache Spark Jobs on Hadoop with Carl ...
Dr. Elephant for Monitoring and Tuning Apache Spark Jobs on Hadoop with Carl ...Databricks
 
Step-by-Step Introduction to Apache Flink
Step-by-Step Introduction to Apache Flink Step-by-Step Introduction to Apache Flink
Step-by-Step Introduction to Apache Flink Slim Baltagi
 
Hibernate performance tuning
Hibernate performance tuningHibernate performance tuning
Hibernate performance tuningMikalai Alimenkou
 
Local Apache NiFi Processor Debug
Local Apache NiFi Processor DebugLocal Apache NiFi Processor Debug
Local Apache NiFi Processor DebugDeon Huang
 
Ai ê·žêčŒìŽê±°
Ai ê·žêčŒìŽê±°Ai ê·žêčŒìŽê±°
Ai ê·žêčŒìŽê±°ë„형 임
 
ORC 2015
ORC 2015ORC 2015
ORC 2015t3rmin4t0r
 
Apache Hadoop YARN – Multi-Tenancy, Capacity Scheduler & Preemption - Stamped...
Apache Hadoop YARN – Multi-Tenancy, Capacity Scheduler & Preemption - Stamped...Apache Hadoop YARN – Multi-Tenancy, Capacity Scheduler & Preemption - Stamped...
Apache Hadoop YARN – Multi-Tenancy, Capacity Scheduler & Preemption - Stamped...StampedeCon
 
Hadoop Strata Talk - Uber, your hadoop has arrived
Hadoop Strata Talk - Uber, your hadoop has arrived Hadoop Strata Talk - Uber, your hadoop has arrived
Hadoop Strata Talk - Uber, your hadoop has arrived Vinoth Chandar
 
RocksDB detail
RocksDB detailRocksDB detail
RocksDB detailMIJIN AN
 
ë”„ëŸŹë‹ì„ 읎용한 얌ꔎ 읞식
ë”„ëŸŹë‹ì„ 읎용한 얌ꔎ ìžì‹ë”„ëŸŹë‹ì„ 읎용한 얌ꔎ 읞식
ë”„ëŸŹë‹ì„ 읎용한 얌ꔎ 읞식if kakao
 
Spark autotuning talk final
Spark autotuning talk finalSpark autotuning talk final
Spark autotuning talk finalRachel Warren
 
A glimpse of cassandra 4.0 features netflix
A glimpse of cassandra 4.0 features   netflixA glimpse of cassandra 4.0 features   netflix
A glimpse of cassandra 4.0 features netflixVinay Kumar Chella
 
Cassandra Day NY 2014: Apache Cassandra & Python for the The New York Times ⚍...
Cassandra Day NY 2014: Apache Cassandra & Python for the The New York Times ⚍...Cassandra Day NY 2014: Apache Cassandra & Python for the The New York Times ⚍...
Cassandra Day NY 2014: Apache Cassandra & Python for the The New York Times ⚍...DataStax Academy
 
Apache Iceberg - A Table Format for Hige Analytic Datasets
Apache Iceberg - A Table Format for Hige Analytic DatasetsApache Iceberg - A Table Format for Hige Analytic Datasets
Apache Iceberg - A Table Format for Hige Analytic DatasetsAlluxio, Inc.
 
Hive 3 a new horizon
Hive 3  a new horizonHive 3  a new horizon
Hive 3 a new horizonArtem Ervits
 
Cloudera Impala Internals
Cloudera Impala InternalsCloudera Impala Internals
Cloudera Impala InternalsDavid Groozman
 

Was ist angesagt? (20)

Patterns and Operational Insights from the First Users of Delta Lake
Patterns and Operational Insights from the First Users of Delta LakePatterns and Operational Insights from the First Users of Delta Lake
Patterns and Operational Insights from the First Users of Delta Lake
 
Dr. Elephant for Monitoring and Tuning Apache Spark Jobs on Hadoop with Carl ...
Dr. Elephant for Monitoring and Tuning Apache Spark Jobs on Hadoop with Carl ...Dr. Elephant for Monitoring and Tuning Apache Spark Jobs on Hadoop with Carl ...
Dr. Elephant for Monitoring and Tuning Apache Spark Jobs on Hadoop with Carl ...
 
Step-by-Step Introduction to Apache Flink
Step-by-Step Introduction to Apache Flink Step-by-Step Introduction to Apache Flink
Step-by-Step Introduction to Apache Flink
 
Hibernate performance tuning
Hibernate performance tuningHibernate performance tuning
Hibernate performance tuning
 
Local Apache NiFi Processor Debug
Local Apache NiFi Processor DebugLocal Apache NiFi Processor Debug
Local Apache NiFi Processor Debug
 
Ai ê·žêčŒìŽê±°
Ai ê·žêčŒìŽê±°Ai ê·žêčŒìŽê±°
Ai ê·žêčŒìŽê±°
 
ORC 2015
ORC 2015ORC 2015
ORC 2015
 
Apache Hadoop YARN – Multi-Tenancy, Capacity Scheduler & Preemption - Stamped...
Apache Hadoop YARN – Multi-Tenancy, Capacity Scheduler & Preemption - Stamped...Apache Hadoop YARN – Multi-Tenancy, Capacity Scheduler & Preemption - Stamped...
Apache Hadoop YARN – Multi-Tenancy, Capacity Scheduler & Preemption - Stamped...
 
Hadoop Strata Talk - Uber, your hadoop has arrived
Hadoop Strata Talk - Uber, your hadoop has arrived Hadoop Strata Talk - Uber, your hadoop has arrived
Hadoop Strata Talk - Uber, your hadoop has arrived
 
RocksDB detail
RocksDB detailRocksDB detail
RocksDB detail
 
ë”„ëŸŹë‹ì„ 읎용한 얌ꔎ 읞식
ë”„ëŸŹë‹ì„ 읎용한 얌ꔎ ìžì‹ë”„ëŸŹë‹ì„ 읎용한 얌ꔎ 읞식
ë”„ëŸŹë‹ì„ 읎용한 얌ꔎ 읞식
 
Spark autotuning talk final
Spark autotuning talk finalSpark autotuning talk final
Spark autotuning talk final
 
A glimpse of cassandra 4.0 features netflix
A glimpse of cassandra 4.0 features   netflixA glimpse of cassandra 4.0 features   netflix
A glimpse of cassandra 4.0 features netflix
 
Cassandra Day NY 2014: Apache Cassandra & Python for the The New York Times ⚍...
Cassandra Day NY 2014: Apache Cassandra & Python for the The New York Times ⚍...Cassandra Day NY 2014: Apache Cassandra & Python for the The New York Times ⚍...
Cassandra Day NY 2014: Apache Cassandra & Python for the The New York Times ⚍...
 
Apache Ranger
Apache RangerApache Ranger
Apache Ranger
 
Upgrading HDFS to 3.3.0 and deploying RBF in production #LINE_DM
Upgrading HDFS to 3.3.0 and deploying RBF in production #LINE_DMUpgrading HDFS to 3.3.0 and deploying RBF in production #LINE_DM
Upgrading HDFS to 3.3.0 and deploying RBF in production #LINE_DM
 
Apache Iceberg - A Table Format for Hige Analytic Datasets
Apache Iceberg - A Table Format for Hige Analytic DatasetsApache Iceberg - A Table Format for Hige Analytic Datasets
Apache Iceberg - A Table Format for Hige Analytic Datasets
 
Angular
AngularAngular
Angular
 
Hive 3 a new horizon
Hive 3  a new horizonHive 3  a new horizon
Hive 3 a new horizon
 
Cloudera Impala Internals
Cloudera Impala InternalsCloudera Impala Internals
Cloudera Impala Internals
 

Ähnlich wie Hibernate performance tuning

Hibernate Performance Tuning (JEEConf 2012)
Hibernate Performance Tuning (JEEConf 2012)Hibernate Performance Tuning (JEEConf 2012)
Hibernate Performance Tuning (JEEConf 2012)Sander Mak (@Sander_Mak)
 
DevOps, Databases and The Phoenix Project UGF4042 from OOW14
DevOps, Databases and The Phoenix Project UGF4042 from OOW14DevOps, Databases and The Phoenix Project UGF4042 from OOW14
DevOps, Databases and The Phoenix Project UGF4042 from OOW14Kyle Hailey
 
Kscope 14 Presentation : Virtual Data Platform
Kscope 14 Presentation : Virtual Data PlatformKscope 14 Presentation : Virtual Data Platform
Kscope 14 Presentation : Virtual Data PlatformKyle Hailey
 
Tune up Yarn and Hive
Tune up Yarn and HiveTune up Yarn and Hive
Tune up Yarn and Hiverxu
 
2019 StartIT - Boosting your performance with Blackfire
2019 StartIT - Boosting your performance with Blackfire2019 StartIT - Boosting your performance with Blackfire
2019 StartIT - Boosting your performance with BlackfireMarko Mitranić
 
Production optimization with React and Webpack
Production optimization with React and WebpackProduction optimization with React and Webpack
Production optimization with React and Webpackk88hudson
 
Resourceslab fixed
Resourceslab fixedResourceslab fixed
Resourceslab fixedJoanne Scouler
 
Agile Data: revolutionizing data and database cloning
Agile Data: revolutionizing data and database cloningAgile Data: revolutionizing data and database cloning
Agile Data: revolutionizing data and database cloningKyle Hailey
 
Drupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp NorthDrupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp NorthPhilip Norton
 
Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...
Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...
Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...DataWorks Summit
 
Performance Analysis of Idle Programs
Performance Analysis of Idle ProgramsPerformance Analysis of Idle Programs
Performance Analysis of Idle Programsgreenwop
 
Redux at scale
Redux at scaleRedux at scale
Redux at scaleinovia
 
10 tips for Redux at scale
10 tips for Redux at scale10 tips for Redux at scale
10 tips for Redux at scaleinovia
 
Iac d.damyanov 4.pptx
Iac d.damyanov 4.pptxIac d.damyanov 4.pptx
Iac d.damyanov 4.pptxDimitar Damyanov
 
Data Virtualization: revolutionizing database cloning
Data Virtualization: revolutionizing database cloningData Virtualization: revolutionizing database cloning
Data Virtualization: revolutionizing database cloningKyle Hailey
 
Aura LA GDG - July 17-2017
Aura LA GDG - July 17-2017Aura LA GDG - July 17-2017
Aura LA GDG - July 17-2017Kristan Uccello
 
EMC Documentum - xCP 2.x Troubleshooting
EMC Documentum - xCP 2.x TroubleshootingEMC Documentum - xCP 2.x Troubleshooting
EMC Documentum - xCP 2.x TroubleshootingHaytham Ghandour
 
Performant Django - Ara Anjargolian
Performant Django - Ara AnjargolianPerformant Django - Ara Anjargolian
Performant Django - Ara AnjargolianHakka Labs
 

Ähnlich wie Hibernate performance tuning (20)

Hibernate Performance Tuning (JEEConf 2012)
Hibernate Performance Tuning (JEEConf 2012)Hibernate Performance Tuning (JEEConf 2012)
Hibernate Performance Tuning (JEEConf 2012)
 
DevOps, Databases and The Phoenix Project UGF4042 from OOW14
DevOps, Databases and The Phoenix Project UGF4042 from OOW14DevOps, Databases and The Phoenix Project UGF4042 from OOW14
DevOps, Databases and The Phoenix Project UGF4042 from OOW14
 
Kscope 14 Presentation : Virtual Data Platform
Kscope 14 Presentation : Virtual Data PlatformKscope 14 Presentation : Virtual Data Platform
Kscope 14 Presentation : Virtual Data Platform
 
Tune up Yarn and Hive
Tune up Yarn and HiveTune up Yarn and Hive
Tune up Yarn and Hive
 
2019 StartIT - Boosting your performance with Blackfire
2019 StartIT - Boosting your performance with Blackfire2019 StartIT - Boosting your performance with Blackfire
2019 StartIT - Boosting your performance with Blackfire
 
Production optimization with React and Webpack
Production optimization with React and WebpackProduction optimization with React and Webpack
Production optimization with React and Webpack
 
Resourceslab fixed
Resourceslab fixedResourceslab fixed
Resourceslab fixed
 
Resource lab
Resource labResource lab
Resource lab
 
Agile Data: revolutionizing data and database cloning
Agile Data: revolutionizing data and database cloningAgile Data: revolutionizing data and database cloning
Agile Data: revolutionizing data and database cloning
 
Drupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp NorthDrupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp North
 
Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...
Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...
Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...
 
Performance Analysis of Idle Programs
Performance Analysis of Idle ProgramsPerformance Analysis of Idle Programs
Performance Analysis of Idle Programs
 
Redux at scale
Redux at scaleRedux at scale
Redux at scale
 
10 tips for Redux at scale
10 tips for Redux at scale10 tips for Redux at scale
10 tips for Redux at scale
 
Iac d.damyanov 4.pptx
Iac d.damyanov 4.pptxIac d.damyanov 4.pptx
Iac d.damyanov 4.pptx
 
Data Virtualization: revolutionizing database cloning
Data Virtualization: revolutionizing database cloningData Virtualization: revolutionizing database cloning
Data Virtualization: revolutionizing database cloning
 
Security lab
Security labSecurity lab
Security lab
 
Aura LA GDG - July 17-2017
Aura LA GDG - July 17-2017Aura LA GDG - July 17-2017
Aura LA GDG - July 17-2017
 
EMC Documentum - xCP 2.x Troubleshooting
EMC Documentum - xCP 2.x TroubleshootingEMC Documentum - xCP 2.x Troubleshooting
EMC Documentum - xCP 2.x Troubleshooting
 
Performant Django - Ara Anjargolian
Performant Django - Ara AnjargolianPerformant Django - Ara Anjargolian
Performant Django - Ara Anjargolian
 

Mehr von Sander Mak (@Sander_Mak)

Scalable Application Development @ Picnic
Scalable Application Development @ PicnicScalable Application Development @ Picnic
Scalable Application Development @ PicnicSander Mak (@Sander_Mak)
 
Event-sourced architectures with Akka
Event-sourced architectures with AkkaEvent-sourced architectures with Akka
Event-sourced architectures with AkkaSander Mak (@Sander_Mak)
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painSander Mak (@Sander_Mak)
 
The Ultimate Dependency Manager Shootout (QCon NY 2014)
The Ultimate Dependency Manager Shootout (QCon NY 2014)The Ultimate Dependency Manager Shootout (QCon NY 2014)
The Ultimate Dependency Manager Shootout (QCon NY 2014)Sander Mak (@Sander_Mak)
 
Cross-Build Injection attacks: how safe is your Java build?
Cross-Build Injection attacks: how safe is your Java build?Cross-Build Injection attacks: how safe is your Java build?
Cross-Build Injection attacks: how safe is your Java build?Sander Mak (@Sander_Mak)
 

Mehr von Sander Mak (@Sander_Mak) (20)

Scalable Application Development @ Picnic
Scalable Application Development @ PicnicScalable Application Development @ Picnic
Scalable Application Development @ Picnic
 
Coding Your Way to Java 13
Coding Your Way to Java 13Coding Your Way to Java 13
Coding Your Way to Java 13
 
Coding Your Way to Java 12
Coding Your Way to Java 12Coding Your Way to Java 12
Coding Your Way to Java 12
 
Java Modularity: the Year After
Java Modularity: the Year AfterJava Modularity: the Year After
Java Modularity: the Year After
 
Desiging for Modularity with Java 9
Desiging for Modularity with Java 9Desiging for Modularity with Java 9
Desiging for Modularity with Java 9
 
Modules or microservices?
Modules or microservices?Modules or microservices?
Modules or microservices?
 
Migrating to Java 9 Modules
Migrating to Java 9 ModulesMigrating to Java 9 Modules
Migrating to Java 9 Modules
 
Java 9 Modularity in Action
Java 9 Modularity in ActionJava 9 Modularity in Action
Java 9 Modularity in Action
 
Java modularity: life after Java 9
Java modularity: life after Java 9Java modularity: life after Java 9
Java modularity: life after Java 9
 
Provisioning the IoT
Provisioning the IoTProvisioning the IoT
Provisioning the IoT
 
Event-sourced architectures with Akka
Event-sourced architectures with AkkaEvent-sourced architectures with Akka
Event-sourced architectures with Akka
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
 
The Ultimate Dependency Manager Shootout (QCon NY 2014)
The Ultimate Dependency Manager Shootout (QCon NY 2014)The Ultimate Dependency Manager Shootout (QCon NY 2014)
The Ultimate Dependency Manager Shootout (QCon NY 2014)
 
Modular JavaScript
Modular JavaScriptModular JavaScript
Modular JavaScript
 
Modularity in the Cloud
Modularity in the CloudModularity in the Cloud
Modularity in the Cloud
 
Cross-Build Injection attacks: how safe is your Java build?
Cross-Build Injection attacks: how safe is your Java build?Cross-Build Injection attacks: how safe is your Java build?
Cross-Build Injection attacks: how safe is your Java build?
 
Scala & Lift (JEEConf 2012)
Scala & Lift (JEEConf 2012)Scala & Lift (JEEConf 2012)
Scala & Lift (JEEConf 2012)
 
Akka (BeJUG)
Akka (BeJUG)Akka (BeJUG)
Akka (BeJUG)
 
Fork Join (BeJUG 2012)
Fork Join (BeJUG 2012)Fork Join (BeJUG 2012)
Fork Join (BeJUG 2012)
 
Fork/Join for Fun and Profit!
Fork/Join for Fun and Profit!Fork/Join for Fun and Profit!
Fork/Join for Fun and Profit!
 

KĂŒrzlich hochgeladen

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel AraĂșjo
 

KĂŒrzlich hochgeladen (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

Hibernate performance tuning

  • 2. Outline Optimization Lazy loading Examples ‘from the trenches’ Search queries Large collections Batching Odds & Ends
  • 4. Hibernate Sucks! ... because it’s slow
  • 5. Hibernate Sucks! ... because it’s slow ‘The problem is sort of cultural [..] developers use Hibernate because they are uncomfortable with SQL and with RDBMSes. You should be very comfortable with SQL and JDBC before you start using Hibernate - Hibernate builds on JDBC, it doesn’t replace it. That is the cost of extra abstraction [..] save yourself effort, pay attention to the database at all stages of development. - Gavin King (creator)
  • 6. Optimization is hard Performance blamed on? Framework <-> You How to optimize? When to optimize? Production vs. development Preserve correctness at all times Unit tests ok, but not enough
  • 7. Optimization is hard Performance blamed on? Framework <-> You How to optimize? When to optimize? Production vs. development Preserve correctness at all times Unit tests ok, but not enough Premature optimization is the root of all evil - Donald Knuth
  • 8. Optimization guidelines Always measure Establish baseline and measure improvement Be prepared to detect performance degradation! Favor obvious over obscure Even if latter performs better Know your RDBMS (hook up with a good DBA) Details do matter Database is not a dumb ‘bit-bucket’
  • 9. Optimization guidelines Measurement Ensure stable, production-like environment Measure time and space Time: isolate timings in different layers Space: more heap -> longer GC -> slower Try to measure in RDBMS as well Memory usage (hot cache or disk thrashing?) Query plans Make many measurements
  • 10. Optimization guidelines Measurement Ensure stable, production-like environment Measure time and space Time: isolate timings in different layers Space: more heap -> longer GC -> slower Try to measure in RDBMS as well Memory usage (hot cache or disk thrashing?) Query plans Make many measurements Remember: measurements are relative
  • 11. Optimization guidelines Practical ProïŹler on DAO/Session.query() methods VisualVM etc. for heap usage Also: JRockit Mission Control Hibernate JMX <property name="hibernate.generate_statistics">true </property> RDBMS monitoring tools
  • 12. Optimization guidelines Practical Example from BMG tuning session:
  • 13. Analyzing Hibernate Log SQL: <property name="show_sql">true</property> <property name="format_sql">true</property> Log4J conïŹguration: org.hibernate -> DEBUG org.hibernate.type -> FINE (see bound params) Or use P6Spy to snoop on JDBC connection
  • 14. Analyzing Hibernate Log SQL: <property name="show_sql">true</property> <property name="format_sql">true</property> Log4J conïŹguration: org.hibernate -> DEBUG org.hibernate.type -> FINE (see bound params) Or use P6Spy to snoop on JDBC connection
  • 17. Lazy loading One entity to rule them all Request Mostly sane defaults: 1..1 @OneToOne, @OneToMany, User @ManyToMany: LAZY 1..* *..1 @ManyToOne : EAGER Due to JPA spec. Authorization *..1 Global 1..* Company Company
  • 18. Lazy loading Request 1..1 User 1..* *..1 Authorization *..1 Global 1..* Company Company
  • 19.
  • 21. Lazy loading N+1 Selects problem Select list of N users HQL: SELECT u FROM User Authorizations necessary: SQL 1 query: SELECT * FROM User N select queries on LEFT JOIN Company c Authorization executed! WHERE u.worksForCompany = c.id Solution: FETCH JOINS
  • 22. Lazy loading N+1 Selects problem Select list of N users HQL: SELECT u FROM User Authorizations necessary: SQL N queries: SELECT * FROM Authorization N select queries on WHERE userId = N Authorization executed! Solution: FETCH JOINS
  • 23. Lazy loading N+1 Selects problem Select list of N users HQL: SELECT u FROM User JOIN FETCH u.authorizations Authorizations necessary: SQL 1 query: N select queries on SELECT * FROM User Authorization executed! LEFT JOIN Company c LEFT OUTER JOIN Authorization ON .. WHERE Solution: u.worksForCompany = c.id FETCH JOINS
  • 24. Lazy loading Some guidelines Laziness by default = mostly good However, architectural impact: Session lifetime (‘OpenSessionInView’ pattern) Extended Persistence Context Proxy usage (runtime code generation) Eagerness can be forced with HQL/JPAQL/Criteria But eagerness cannot be revoked exception: Session.load()/EntityManager.getReference()
  • 26. Search queries User 1..* *..1 Authorization *..1 Global 1..* Company Company
  • 27. Search queries Obvious solution: Too much information! Use summary objects: UserSummary = POJO not attached, only necessary ïŹelds (no relations)
  • 28. Search queries Obvious solution: Too much information! Use summary objects: UserSummary = POJO not attached, only necessary ïŹelds (no relations) Or: drop down to JDBC to fetch id + ïŹelds
  • 29. Search queries Alternative: Taking it further: Pagination in queries, not in app. code Extra count query may be necessary (totals) Ordering necessary for paging!
  • 30. Search queries Subtle: Alternative: effect of applying setMaxResults “The or setFirstResult to a query involving fetch joins over collections is undeïŹned” Taking it further: Cause: the emitted join possibly returns several rows per entity. So LIMIT, rownums, TOP cannot be used! Instead Hibernate must fetch all rows WARNING: firstResult/maxResults specified with Pagination in queries, not in app. code collection fetch; applying in memory! Extra count query may be necessary (totals) Ordering necessary for paging!
  • 32. Large collections Frontend: Request CompanyGroup 1..* Backend: Company CompanyGroup 1..* Meta-data Company read-only entity, CompanyInGroup backed by expensive view *..1 Company
  • 33. Large collections Frontend: Request CompanyGroup 1..* Backend: Company CompanyGroup 1..* Meta-data CompanyInGroup *..1 Company
  • 34. Large collections Frontend: Request CompanyGroup 1..* Backend: Company CompanyGroup 1..* Meta-data CompanyInGroup *..1 Company
  • 35. Large collections Opening large groups sluggish Improved performance: Fetches many uninitialized collections in 1 query Also possible on entity: Request CompanyGroup 1..* Company
  • 36. Large collections Opening large groups sluggish Improved performance: Fetches many uninitialized collections in 1 query Also possible on entity: Request CompanyGroup 1..* Company Better solution in hindsight: fetch join
  • 37. Large collections Saving large group slow: >15 sec. Problem: Hibernate inserts row by row Query creation overhead, network latency Solution: <property name="hibernate.jdbc.batch_size">100 </property> Enables JDBC batched statements Caution: global property Request CompanyGroup Also: <property name="hibernate.order_inserts">true 1..* </property> Company <property name="hibernate.order_updates">true </property>
  • 38. Large collections Frontend: Request CompanyGroup 1..* Backend: Company CompanyGroup 1..* Meta-data CompanyInGroup *..1 Company
  • 39. Large collections Backend: CompanyGroup 1..* Meta-data CompanyInGroup *..1 Company
  • 40. Large collections Process CreateGroup (Soap) Business Service Service CreateGroup took ~10 min. for 1000 companies @BatchSize on Company improved demarshalling JDBC batch_size property marginal improvement INFO: INSERT INTO CompanyInGroup VALUES (?,...,?) INFO: SELECT @identity INFO: INSERT INTO CompanyInGroup VALUES (?,...,?) INFO: SELECT @identity .. 1000 times CompanyGroup 1..* Meta-data Insert/select interleaved: due to gen. id CompanyInGroup *..1 Company
  • 41. Large collections Process CreateGroup (Soap) Business Service Service Solution: generate id in app. (not always feasible) Running in ~3 minutes with batched inserts Next problem: heap usage spiking Use StatelessSession ✩ Bypass ïŹrst-level cache ✩ No automatic dirty checking CompanyGroup ✩ Bypass Hibernate event model and interceptors 1..* Meta-data ✩ No cascading of operations CompanyInGroup ✩ Collections on entities are ignored *..1 Company
  • 42. Large collections Process CreateGroup (Soap) Business Service Service Solution: generate id in app. (not always feasible) Running in ~3 minutes with batched inserts Next problem: heap usage spiking Use StatelessSession CompanyGroup 1..* Meta-data CompanyInGroup *..1 Company
  • 43. Large collections Process CreateGroup (Soap) Business Service Service Now ~1 min., everybody happy! CompanyGroup 1..* Meta-data CompanyInGroup *..1 Company
  • 44. Large collections Process CreateGroup (Soap) Business Service Service Now ~1 min., everybody happy! Data loss detected! CompanyGroup 1..* Meta-data CompanyInGroup *..1 Company
  • 45. Large collections Process CreateGroup (Soap) Business Service Service Data loss detected! StatelessSession and JDBC batch_size bug Only ‘full’ batches are performed! HHH-4042: Closed, won’t ïŹx : CompanyGroup 1..* Meta-data CompanyInGroup *..1 Company
  • 47. Query hints Speed up read-only service calls: Hibernate Query.setHint(): Also: never use 2nd level cache just ‘because we can’
  • 48. Query hints Speed up read-only service calls: Hibernate Query.setHint(): Also: never use 2nd level cache just ‘because we can’ @org.hibernate.annotations.Entity(mutable = false)
  • 49. Large updates Naive approach: Entities are not always necessary: Changes are not reïŹ‚ected in persistence context With optimistic concurrency: VERSIONED keyword
  • 50. Large updates Naive approach: Entities are not always necessary: Changes are not reïŹ‚ected in persistence context With optimistic concurrency: VERSIONED keyword Consider use of stored procedures
  • 51. Dynamic updates @org.hibernate.annotations.Entity (dynamicInsert = true, dynamicUpdate = true ) Only changed columns updated/inserted BeneïŹcial for tables with many columns Downsides Runtime SQL generation overhead No PreparedStatement (caching) used anymore
  • 52. Cherish your database Data and schema probably live longer than app. Good indexes make a world of difference Stored procedures etc. are not inherently evil Do not let Hibernate dictate your schema Though sometimes you are forced There are other solutions (there I said it) Read the Endeavour JPA Guideline!

Hinweis der Redaktion

  1. Typisch meer &amp;#x2018;kunst dan wetenschap&amp;#x2019;. Mijn aanpak niet heilig, hoor graag tijdens de presentatie ideeen &amp;#x2018;wat als je dit of dat had gedaan&amp;#x2019;, goed om te discussieren.
  2. Preserving correctness: unit tests! However, the more you reach the edges of the DBMS, the easier you will hit an obscure bug in query optimizer, caching strategy etc.
  3. Know your RDBMS! Database independence is nice when porting is necessary, but focus on particular DB for production situation (document!), that is what counts! (once you get into nitty-gritty opt. details, you will have to know the RDBMS intimately)
  4. Know your RDBMS! Database independence is nice when porting is necessary, but focus on particular DB for production situation (document!), that is what counts! (once you get into nitty-gritty opt. details, you will have to know the RDBMS intimately)
  5. Know your RDBMS! Database independence is nice when porting is necessary, but focus on particular DB for production situation (document!), that is what counts! (once you get into nitty-gritty opt. details, you will have to know the RDBMS intimately)
  6. Beware: you might retrieve your whole database in one go... Code example: will load Company eager, Auths. lazy
  7. Beware: you might retrieve your whole database in one go... Code example: will load Company eager, Auths. lazy
  8. Zonder Hibernate zou je niet eens over zo&amp;#x2019;n soort scenario nadenken, nu moet je wel.
  9. Zonder Hibernate zou je niet eens over zo&amp;#x2019;n soort scenario nadenken, nu moet je wel.
  10. Zonder Hibernate zou je niet eens over zo&amp;#x2019;n soort scenario nadenken, nu moet je wel.
  11. Zelfde overwegingen gelden voor reporting queries, zoveel mogelijk in de query oplossen en geen entities teruggeven als niet nodig
  12. Example: 20 groups with uninitialized collections, access first collection: all are initialized with 1 query. Measured: opening first group was slightly slower, general user experience better
  13. stateless session ideaal for fire-and-forget service calls, minder in user-facing applicatie waar consistent houden persistence context van belang is.
  14. stateless session ideaal for fire-and-forget service calls, minder in user-facing applicatie waar consistent houden persistence context van belang is.
  15. Hibernate does some optimizing for read-only entities: It saves execution time by not dirty-checking simple properties or single-ended associations. It saves memory by deleting database snapshot cache increases load on memory, possibly more GC pauses for app. if co-located with application
  16. Interesting: all instances of entity are evicted from second level cache with such a query, even if WHERE clause limits affected entities Also, no events fired as Hibernate normally would do.
  17. Interesting: all instances of entity are evicted from second level cache with such a query, even if WHERE clause limits affected entities Also, no events fired as Hibernate normally would do.