Skip to the page

JPA and Hibernate · core

Lazy loading, N+1 and open-in-view

Associations should be lazy and fetched per use case. Touching lazy data in a loop causes N+1 queries. Open-in-view hides the problem and holds connections.

The notes

What you must know

  • JPA defaults: @ManyToOne and @OneToOne are EAGER. @OneToMany and @ManyToMany are LAZY.
  • Eager is fixed in the mapping. A JPQL query for 500 orders does not join the eager customer automatically: Hibernate runs extra selects. Make all associations LAZY and fetch per use case.
  • Fetch per use case with join fetch, @EntityGraph or DTO projections. getReferenceById() returns a proxy without a SELECT.
  • N+1: one query for 100 orders, then a query per order for items and per item for the product. Fix with a fetch join or an entity graph. Check with SQL logging, Hibernate statistics or a datasource proxy in tests.
  • A collection fetch with Pageable makes Hibernate page in memory (a warning is logged). Page ids first, then fetch those orders with their items.
  • Fetching two List collections at once gives MultipleBagFetchException. Use Sets or separate queries.
  • LazyInitializationException: a lazy association was touched after the session closed.
  • Spring Boot turns open-in-view on by default and logs a warning. It keeps an EntityManager open for the whole request, so lazy loads work in the controller or while JSON is written. Cost: hidden N+1 and a database connection held for the rest of the request. For APIs turn it off, load what each use case needs inside the service transaction, and return DTOs, not entities. Bad fixes: EAGER everywhere, Hibernate.initialize everywhere, enable_lazy_load_no_trans.

The red pen

Common traps: mistake → fix

  • Mistake: EAGER fixes LazyInitializationException

    Fix: it moves the cost to every query.

  • Mistake: Lazy collections load in one query when I loop

    Fix: each access runs its own query.

  • Mistake: Open-in-view is harmless

    Fix: it holds connections and hides N+1 queries.

Easy to hard

Questions interviewers ask, easy to hard

  1. What are the default fetch types? Do you make everything lazy?
  2. The orders page fires 201 queries. Why and how do you fix it?
  3. A job throws LazyInitializationException but the controller works. Why?
  4. Would you leave open-in-view on?

Practise

Practise with these questions

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview