Hibernate is a great ORM — until you look at the SQL logs. 100 orders = 101 SQL queries. That’s the N+1 problem and the most common cause of slow JPA applications.
LazyInitializationException¶
Hibernate loads associations lazily by default. Three solutions: Open Session in View (simple, but violates layer separation), DTO pattern (our preference), explicit fetch.
JOIN FETCH¶
JPQL with JOIN FETCH loads the association in a single SQL query. Ideal for a single entity. For lists, beware of the Cartesian product.
@BatchSize¶
@BatchSize(size=20) loads lazy collections in batches of 20 instead of one at a time. 100 orders = 5 SQL queries instead of 100.
Second Level Cache¶
Ehcache for read-mostly data. Query cache for repeated queries. Be careful about cache invalidation.
Rules¶
- Log SQL in development. 2. Use
JOIN FETCHfor single entities. 3. Use@BatchSizefor lists. 4. Apply the DTO pattern. 5. Cache read-mostly data.
Need help with implementation?
Our experts can help with design, implementation, and operations. From architecture to production.
Contact us