Sub topic 12
Open Session in View and lazy loading in controllers
This chapter assumes you know how lazy loading works, how the persistence context ties entities to a transaction, and what an N+1 query looks like. If any of that is unclear, review the earlier chapters first.
What Open Session in View does
Open Session in View (OSIV) keeps the Hibernate session, and so the persistence context, open for the whole web request. It stays open after the service method returns and its transaction ends. A lazy association can then be loaded while the controller or the JSON serializer reads it.
Spring Boot enables OSIV by default. It also logs a warning at startup when spring.jpa.open-in-view is not set explicitly.
Consider this controller, which uses the Author and Book model from earlier:
@RestController
public class AuthorController {
private final AuthorRepository authorRepository;
public AuthorController(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@GetMapping("/authors")
public List<Author> authors() {
return authorRepository.findAll();
}
}With OSIV on, Jackson walks getBooks() during serialization. Each call loads one lazy collection, so you get the N+1 pattern, and it happens in the web layer where the code looks harmless. (A bidirectional mapping like this one also risks infinite recursion in JSON. That is one more reason not to return entities.)
Why this is risky
- Hidden queries. Lazy loads happen in the view layer, far from the code that should have chosen the fetch strategy.
- Connection hold time. The database connection is usually acquired on first use and held until the request ends. Slow serialization or a slow downstream call keeps the connection busy, which can exhaust the pool under load.
- Unclear boundaries. The service no longer defines what data a use case needs.
Turning it off
Set the property explicitly:
spring.jpa.open-in-view=falseNow any lazy association touched after the transaction ends throws LazyInitializationException. This is the intended result. The error appears the first time you run the code, not as a slow endpoint in production.
Fixing the code properly
Do not fall back to FetchType.EAGER. Load what the use case needs inside the service, and return a type that holds only that data.
public record AuthorSummary(String name, int bookCount) {}
@Service
public class AuthorQueryService {
private final AuthorRepository authorRepository;
public AuthorQueryService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Transactional(readOnly = true)
public List<AuthorSummary> summaries() {
return authorRepository.findAllWithBooks().stream()
.map(a -> new AuthorSummary(a.getName(), a.getBooks().size()))
.toList();
}
}The controller then returns List<AuthorSummary>. Everything lazy is resolved inside the transaction, with one query from findAllWithBooks(). For read-only endpoints, a DTO projection can be simpler still.
| Setting | Lazy access in controller | Query visibility | Connection hold |
|---|---|---|---|
| `open-in-view=true` | Works, extra queries | Hidden in the web layer | Until the request ends |
| `open-in-view=false` | Throws exception | Fixed in the service | Only for the transaction |
Exercise
A controller returns an Author entity directly. With spring.jpa.open-in-view=true, the JSON response includes each author's books, and the log shows one query per author. After you set the property to false, the endpoint fails. What exception do you see, and what is the correct fix?
Show answer
You see LazyInitializationException, because the books collection is read after the service transaction has closed the session. The fix is to load the books inside the service, for example with JOIN FETCH or @EntityGraph, and return a DTO such as AuthorSummary. Making the association eager would hide the problem and load the data in every query.