hibernate Tunning

hibernate Tunning

Hibernate’s generated SQL statement is slow !?

I do not agreed on the statement “Hibernate’s generated SQL statement is slow”. Often times, i found out this is because of the developers do not understand the table relationship well, and did some wrong table mappings or misuse the fetch strategies. It will cause Hibernate generated some unnecessary SQL statements or join some unnecessary tables… And developers like to take this excuse and create their own SQL statement to quick fix the bug, and didn’t aware of the core problem will causing more bugs awaiting.


N + 1

https://vladmihalcea.com/n-plus-1-query-problem/

The N+1 query problem happens when the data access framework executed N additional SQL statements to fetch the same data that could have been retrieved when executing the primary SQL query.

The larger the value of N, the more queries will be executed, the larger the performance impact

Screen Shot 2020-11-26 at 10.22.38 PM

FetchType Eager

The FetchType.EAGER strategy is also prone to N+1 query issues. Unfortunately, the @ManyToOne and @OneToOne associations use FetchType.EAGER by default,

** use JOIN FETCH to avoid the N+1 query problem**

FetchType Lazy

Because the post association is fetched lazily, a secondary SQL statement will be executed when accessing the lazy association in order to build the log message.

The fix consists in adding a JOIN FETCH clause to the JPQL query:


Summary

lazy load (many), 使用join fetch, 避免n+1


https://dzone.com/articles/how-identify-and-resilve-n1

https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/appendices/BestPractices.html

https://vladmihalcea.com/hibernate-performance-tuning-tips/

https://www.baeldung.com/hibernate-common-performance-problems-in-logs


https://vladmihalcea.com/the-best-way-to-handle-the-lazyinitializationexception/


https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/performance.html