Skip to content
Commitwise
Menu

What is a LazyInitializationException, and how should you load related data with JPA?

BackendMid-level

In shortIt happens when a lazy association is accessed after the persistence context that loaded the entity is closed. Fix it by loading what the use case needs inside the transaction (fetch joins, entity graphs or DTO projections), not by turning on open-in-view or making everything eager.

Model answer

A lazy association (@OneToMany by default, or @ManyToOne(fetch = LAZY)) is a proxy that loads its data on first access, using the persistence context (Hibernate session) that loaded the parent. If that context is closed, typically because the transaction ended in the service and the controller or a JSON serializer touches the association, Hibernate throws LazyInitializationException.

Good fixes load exactly what the use case needs while the transaction is open:

  • Fetch joins: select o from Order o join fetch o.items where o.id = :id.
  • Entity graphs: @EntityGraph(attributePaths = ["items", "customer"]) on a repository method.
  • DTO projections: query straight into a record (select new OrderSummary(o.id, o.total, c.name) …), which is usually best for read endpoints.

Bad fixes:

  • EAGER everywhere loads associations on every query, including where they’re not needed, and often causes N+1 queries.
  • Open Session in View (spring.jpa.open-in-view, on by default in Spring Boot with a warning) keeps the session open during view rendering, so lazy loads run as extra queries outside any transaction, hiding N+1 problems and holding connections longer. Turn it off and fix the queries.

Map entities to DTOs in the service layer and never serialize entities directly; it couples the API to the schema and triggers lazy loading in the serializer.

What they're looking for

Understanding of the persistence context and lazy proxies, the right fixes (fetch join, @EntityGraph, projections), why EAGER and open-in-view are bad defaults, and the link to the N+1 problem.

Common mistakes

  • Switching associations to FetchType.EAGER.
  • Relying on spring.jpa.open-in-view to make it go away.
  • Returning entities directly from REST controllers.

More backend questions

Esc

Type to search the whole site.