SteelReed

Search

Search posts, questions…

JPA & HibernateQuestion 19 / 24

Middle

When does LazyInitializationException occur? What is open-session-in-view and why turn it off?

Short answer

LazyInitializationException happens when code touches a LAZY relation after the database session has closed, usually while Jackson turns the object into JSON. OSIV keeps the session open for the whole request to hide the error, at the cost of hidden N+1; turn it off.

yes: JOIN FETCH, DTOnoservice opens a transactionAll needed data loaded?return JSON safelyJackson touches LAZYafter the session closedLazyInitializationException

3 points to say:

  1. The real fix: load everything inside the transaction.
  2. Turn OSIV off: spring.jpa.open-in-view=false.
  3. Switching to EAGER is the wrong fix.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.