Java and Spring Level 3 This level · 47 of 56
Hard java spring

Controller returns a JPA entity with a lazy OneToMany?

The 30 second answer

Jackson walks getters and touches the lazy collection. With open-in-view off you get LazyInitializationException wrapped as a message conversion error. With Spring Boot's default open-in-view true it loads during rendering, which causes extra queries, N-plus-one risk, possible infinite recursion on bidirectional mappings, and leaked internal fields. Return DTOs or records, fetch what you need up front, and prefer open-in-view false.

Could you say this in an interview?

Jackson serializes getters → touches the lazy collection. With OSIV off: LazyInitializationException (wrapped as HttpMessageNotWritableException). With Spring Boot's default spring.jpa.open-in-view=true (it logs a warning): it loads silently → extra queries/N+1 during rendering, possible infinite recursion with bidirectional mappings (StackOverflow/JsonMappingException), and you leak internal fields. Fix: return DTOs/records, fetch what you need (JOIN FETCH, @EntityGraph), set open-in-view=false.

Alternate interview scenarios

"LazyInitializationException happens in production but not in dev. Why?"

The code is the same, so I look at what differs in the environment. First, configuration: a profile may set spring.jpa.open-in-view differently, and with it on the session stays open through rendering, so the lazy load quietly works. Second, tests: a test annotated with @Transactional keeps one transaction and session open for the whole test and rolls back at the end, so a lazy access that fails in production passes in the test. Third, data: in dev the collection is often empty, or the entity is already in the persistence context, so no lazy load is needed. Fourth, code paths that only run in production, such as an @Async method, a scheduled job or a message listener that touches the entity after the transaction ended. The fix is the same everywhere: load what the use case needs inside the transaction with a fetch join or an entity graph, and return DTOs.

Sources (3)
  1. Spring Boot — SQL databases / JPA "Open EntityManager in View"docs.spring.io
  2. Hibernate User Guide — Fetchingdocs.jboss.org
  3. Spring Framework testing: Transaction management (test transactions roll back)docs.spring.io
Previous
Next