Sub topic 12
Open Session in View and Lazy Loading in Controllers
This chapter assumes you know basic Spring Boot structure, Spring Data JPA repositories, and the @Entity, @OneToMany and @ManyToOne mappings from the earlier chapters. You should also know what the persistence context is and why lazy associations load on first access. Here you will see how Open Session in View (OSIV) changes where lazy loading can happen, why that hides performance problems, and how to turn it off on purpose.
What Open Session in View does
A lazy association can only load while its persistence context is open. Normally the context lives as long as the transaction. In the service from earlier chapters, authorSummaries() is annotated with @Transactional, so the context closes when the method returns. Any lazy collection that was not touched by then can no longer be loaded.
Open Session in View keeps the persistence context (the EntityManager) open for the whole web request. Spring Boot registers OpenEntityManagerInViewInterceptor by default for servlet web applications. The interceptor binds an EntityManager to the request thread before the controller runs and closes it after the response is rendered.
The result is that entities returned from a service stay managed after the transaction ends. A controller, a view template, or a JSON serializer can then call getBooks() and trigger a lazy load.
Why it exists
Without OSIV, a controller that serializes an entity with an uninitialized lazy collection fails with LazyInitializationException. The error means that Hibernate tried to load a lazy association but had no open session. OSIV avoids that error everywhere. Many applications started working "by magic" once it was enabled, and that is why it is on by default.
Consider this controller, using the Author and Book entities from the example model:
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@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 the books collection of each author while writing the response. Each call initializes a lazy collection with its own query. That is the N+1 problem again, now caused by the serializer rather than by your code. (This example also has a mapping problem. Book points back to Author, so serializing both sides can recurse. Returning entities from controllers is a bad habit for that reason as well.)
Why it hides performance problems
OSIV has three costs that are easy to miss.
- Invisible queries. SQL runs in the controller, the view layer, or a serializer. Nothing in the service shows that the request needs
1 + Nstatements. Code review of the service method will not find it. - Connection holding. With OSIV on, the JDBC connection can stay checked out for longer than the transaction. Hibernate acquires a connection when it first needs one and, by default, releases it after the transaction completes. A lazy load after the transaction acquires a connection again, in auto-commit mode, and holds it until the request ends. Rendering a slow view or calling a slow downstream service while the context is open can keep connections from the pool unavailable to other requests.
- Missing transaction boundaries. Lazy loads in the controller run outside any service transaction. Each load is its own implicit unit of work. Several reads in one request can see different database states, because they no longer share one transaction snapshot.
On a small data set in development, none of this is visible. In production it shows up as slow endpoints and connection pool exhaustion.
Turning it off
Spring Boot logs a warning at startup when OSIV is active and you have not set the property yourself: spring.jpa.open-in-view is enabled by default. To make the choice explicit, set it in application.properties:
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.generate_statistics=true
logging.level.org.hibernate.SQL=DEBUGThe first line disables the interceptor. The other two lines are the detection settings from the earlier chapter on SQL logs and statistics. Keep them while you migrate so that you can see which requests change.
After you disable OSIV, the persistence context lasts only as long as the transaction. Any lazy access after the service method returns throws LazyInitializationException. That is the intended outcome. The failure shows you each place where the request depended on a query nobody planned.
Fixing the failures
The correct fix for a LazyInitializationException is to load what the response needs inside the service, in a planned query. Avoid fixes that only move the lazy load back inside a transaction without addressing the query count.
- Decide what the response contains. List the fields the endpoint returns. Often it is a few values, not whole entities.
- Load exactly that data in the service. Use a DTO projection when you need only some columns, or
JOIN FETCHor@EntityGraphwhen you need entities with an association. - Return DTOs from the controller. Map entities to DTOs inside the transactional service method, so that serialization touches only plain objects.
Here is the earlier summary use case rewritten for a controller without OSIV. The service returns the AuthorBookCount record from the DTO projection chapter, so no lazy loading is possible after the transaction:
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AuthorStatsService {
private final AuthorStatsRepository statsRepository;
public AuthorStatsService(AuthorStatsRepository statsRepository) {
this.statsRepository = statsRepository;
}
@Transactional(readOnly = true)
public List<AuthorBookCount> bookCounts() {
return statsRepository.findAuthorBookCounts();
}
}import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AuthorStatsController {
private final AuthorStatsService statsService;
public AuthorStatsController(AuthorStatsService statsService) {
this.statsService = statsService;
}
@GetMapping("/authors/stats")
public List<AuthorBookCount> stats() {
return statsService.bookCounts();
}
}The request runs one aggregate statement. The controller has nothing lazy to trigger, so it behaves the same with OSIV on or off.
Common mistakes when removing OSIV
| Symptom | Cause | Better fix |
|---|---|---|
| `LazyInitializationException` in a controller | The service returned an entity whose association was never loaded | Fetch it in the service query, or return a DTO |
| Developer adds `FetchType.EAGER` to the mapping | Wants the exception to go away everywhere | Keep the mapping lazy. Fetch per use case |
| Developer calls `getBooks().size()` in the service to "initialize" | Triggers one query per parent, which is N+1 inside the transaction | Use `JOIN FETCH`, `@EntityGraph`, or batch fetching |
| Developer wraps the controller method in `@Transactional` | Recreates OSIV behavior on one endpoint and hides the query count | Move the transaction and the loading into the service |
| Detached entity is accessed after the transaction in a test | Test has no web request, so OSIV never applied | Assert on the service result, using a query-count test |
When keeping it on is reasonable
OSIV is not a defect in every application. Server-rendered applications with small pages, internal tools, and prototypes often run fine with it. If you keep it, do so deliberately:
- Set
spring.jpa.open-in-view=trueexplicitly, which also removes the startup warning and records the decision. - Watch the statement count per request with Hibernate statistics, because OSIV will not warn you about N+1.
- Keep slow external calls out of the request path while the context is open, or move them before or after the part that uses the database.
- Prefer returning DTOs from controllers anyway. It makes the response shape a decision you control, not a side effect of the entity model.
Checking your result
After you fix an endpoint, confirm the change with the tools from earlier chapters. With spring.jpa.open-in-view=false, call the endpoint and read the SQL log. You should see only the statements that the service issued. Then add a query-count test around the service method, so that a future change that reintroduces lazy loading fails the build instead of reaching production.
Exercise
A controller returns List<Author> from authorRepository.findAll(). With OSIV enabled, the endpoint works but the SQL log shows one query for authors plus one per author for books. You then set spring.jpa.open-in-view=false and the endpoint throws LazyInitializationException. Explain why both behaviors happen, and describe a fix that makes the endpoint use one statement.
Show answer
With OSIV enabled, the EntityManager stays open for the whole request, so Jackson can call getBooks() during serialization and each call runs a lazy select, which gives 1 + N statements. With OSIV disabled, the persistence context closes when the repository call's transaction ends, so the same getBooks() call has no open session and Hibernate throws LazyInitializationException. The fix is to load the data in a planned way inside a transactional service method: either a JOIN FETCH or @EntityGraph query that loads authors with their books in one statement and map to a DTO, or a DTO projection with a constructor expression if only some values are needed. The controller then returns DTOs, so serialization triggers no lazy loading.
Exercise
Why does a lazy load that happens after the service transaction ends, with OSIV on, increase the risk of connection pool exhaustion?
Show answer
The lazy load needs a JDBC connection, so Hibernate acquires one outside the transaction and keeps it until the request ends and the EntityManager closes. Any slow work after that point, such as rendering a large view or calling another service, keeps the connection checked out and unavailable to other requests.