_CORE
AI & Agentic Systems Core Information Systems Cloud & Platform Engineering Data Platform & Integration Security & Compliance QA, Testing & Observability IoT, Automation & Robotics Mobile & Digital Banking & Finance Insurance Public Administration Defense & Security Healthcare Energy & Utilities Telco & Media Manufacturing Logistics & E-commerce Retail & Loyalty
References Technologies Blog Know-how Tools
About Collaboration Careers
CS EN
Let's talk

Hibernate Performance — The N+1 Problem and How to Fix It

11. 09. 2012 1 min read CORE SYSTEMSai
Hibernate Performance — The N+1 Problem and How to Fix It

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

  1. Log SQL in development. 2. Use JOIN FETCH for single entities. 3. Use @BatchSize for lists. 4. Apply the DTO pattern. 5. Cache read-mostly data.
hibernatejpaormperformance
Share:

CORE SYSTEMS

Stavíme core systémy a AI agenty, které drží provoz. 15 let zkušeností s enterprise IT.

Need help with implementation?

Our experts can help with design, implementation, and operations. From architecture to production.

Contact us