Hibernate performance
tuning
Mikalai Alimenkou/Igor Dmitriev
http://xpinjection.com
@xpinjection
Disclaimer
This is only my
personal experience
You could follow code samples
https://github.com/xpinjection/hibernate-performance
What Hibernate really does?
Full execution chain
How to measure
• Hibernate statistics with
• Benchmarks with JMH:
– http://openjdk.java.net/projects/code-tools/jmh/
How to understand and trace
• Datasource proxy:
– https://github.com/ttddyy/datasource-proxy
– https://github.com/p6spy/p6spy
• Queries counting interceptor:
– https://github.com/vladmihalcea/db-util
• Log and format SQL statements
Demo database schema
JDBC tuning
• Use good implementation of connection pool
• Batching, fetching
• Switch to native queries where performance is
critical
• Do direct JDBC stuff with Session doWork
N + 1, lazy loading issues
• Eager load
• Entity graphs
• Fetch modes
• Fetch profiles
• Query batching
Operations batching
• Flush Session state to avoid memory issues
• Use JDBC batching options
in order to mix statements for different tables
• Deletes are batched only for the same table
Second level cache
Cache providers and strategies
Query cache
Mark lightweight requests
• Read-only flag for transactions
• Choose appropriate transaction isolation level
• Annotate entity as immutable if it is not
updated anywhere
• Use StatelessSession for some operations
Don’t use entities everywhere
• ResultTransformer and Transformers
• Fields map instead of object
• @SqlResultSetMapping
• Direct mapping on DTO
Don’t update all columns
• Dynamic insert, update
• Update only changed columns
• Be careful with number of PreparedStatement
Slow ID generation
• Id generator mapping
• Don’t use GenerationType.AUTO, use
GenerationType.SEQUENCE instead
• Try to generate ID/PK in the
code, not delegate to Hibernate
Other advices
• Use native queries if really helpful:
– “ORDER BY NULL” or “DELETE with JOIN” in
MySQL
– Effective data removal
• Don’t use lists, arrays and ordering in
Hibernate
Start thinking in CQRS way
When we really need to use ORM?
Resources
• https://vladmihalcea.com/presentations/
• https://vladmihalcea.com/tutorials/hibernate/
• http://jeeconf.com/archive/jeeconf-
2012/materials/hibernate-performance/
• https://docs.jboss.org/hibernate/orm/5.0/manual/en-
US/html_single/#performance
• http://jeeconf.com/program/hibernate-how-the-magic-
is-really-done/
• http://jeeconf.com/program/hibernate-performance-
tuning/
Books to read
@xpinjection
http://xpinjection.com
mikalai.alimenkou@xpinjection.com
ihor.dmitriiev@gmail.com

Hibernate performance tuning

Editor's Notes

  • #7 TODO: поставить правильную ссылку и перегенерить QR код
  • #14 На демо показываем: как сконфигурировать и показывать статистику как контролировать количество запросов в тестах
  • #17 На демо показываем: N + 1 проблему разные стратегии вычитки (join, subselect, batching) применение графов сущностей blind guess loading (несколько наперед чтобы экономить запросы) применение фетча для одного запроса !!! объяснить
  • #19 На демо показываем: - вставка пачкой удаление пачкой обновление пачкой
  • #23 На демо показываем: как настроить second level кэш !!! не показывыем как работает second level кэш как что кешируется (сущности, коллекции) !!! не показываем query cache и его взаимодействие с second level cache
  • #25 На демо показываем: как отключается dirty checking пример работы через StatelessSession !!! не показывать
  • #27 На демо показываем: примеры трансформации результов маппинг на DTO прямой
  • #29 На демо показываем: - вставку и обновление сущности с включенными флагами
  • #31 TODO: добавить визуализацию
  • #35 TODO: добавить еще ресурсов