Skip to content
javahacks.dev
Spring MVC

How to Disable Open in View Safely in Spring Boot Apps

Disable spring.jpa.open-in-view safely: find lazy loads outside a transaction, fix them with fetch joins and DTO projections, and prove it with tests.

8 min read
Summarize in AI
Flat illustration of a start button surrounded by Spring Boot starters, with the Spring Boot, Spring and Hibernate logos.

Turning off Open Session in View takes a single property and is, for a service with real traffic, one of the more valuable cleanups available: the database connection is released as soon as the transaction ends, hidden queries during serialisation disappear and the transaction boundary becomes the unit of consistency again. The reason teams hesitate is the second half of the work. With the interceptor gone, every place that read a lazy association outside a transaction now throws LazyInitializationException, and the application cannot be trusted until they are all found and fixed. This post is a procedure for doing that without a production incident: find the cases, choose a fix for each, convert the service layer to return complete data and lock the result in with tests. The concepts are in Open Session in View explained.

Step 1: measure the current behaviour

Before changing anything, record two baselines so you can see the effect: how many queries each important endpoint issues, and how long connections are held. Enable Hibernate statistics for a test run, and the Hikari metrics in staging:

properties
spring.jpa.properties.hibernate.generate_statistics=true
logging.level.org.hibernate.stat=DEBUG
Text
Session Metrics {
    4510200 nanoseconds spent acquiring 1 JDBC connections;
    ...
    11 JDBC statements executed
}

An endpoint that "should" take two queries and takes eleven is already telling you where lazy loading is hiding. Keep the numbers for the comparison at the end.

Step 2: turn it off where you can see the damage

Set the property in the test profile first, not in production:

src/test/resources/application-test.propertiesproperties
spring.jpa.open-in-view=false

Run the existing tests. Whatever fails with LazyInitializationException, could not initialize proxy - no Session, is a place that depended on the interceptor. A well tested application will show most of its dependencies right away. For the rest, deploy to a staging environment with the property off and exercise the application, ideally with a replay of production like requests. Check the error logs for the exception:

Shell
grep -c "LazyInitializationException" app.log
grep "LazyInitializationException" app.log | sed -E 's/.*role: ([A-Za-z0-9_.]+).*/\1/' | sort | uniq -c | sort -rn
Text
     14 dev.javahacks.orders.Order.lines
      6 dev.javahacks.orders.Order.customer
      3 dev.javahacks.catalog.Product.tags

The second command groups failures by the association that was touched, which gives you a work list ordered by frequency: Order.lines is the first thing to fix. The stack trace for each shows the call site, usually a mapper, a serialiser or a template.

Step 3: choose a fix for each

There are four ways to give a caller the data it needs, in the order to prefer them.

A DTO projection. If the endpoint needs a few fields, ask the database for exactly those, and never load the entity at all:

java
public interface OrderRepository extends JpaRepository<Order, Long> {

    @Query("""
            select new dev.javahacks.orders.OrderSummary(o.id, o.status, c.name, count(l))
            from Order o join o.customer c left join o.lines l
            where o.id = :id
            group by o.id, o.status, c.name
            """)
    Optional<OrderSummary> summary(@Param("id") long id);
}

public record OrderSummary(long id, String status, String customerName, long lineCount) {}

One query, no entities, no proxies, nothing lazy to trip over. This is the best fix for read endpoints. The technique is in DTO projections with records.

A join fetch. When you need the entity and a specific association, fetch the association in the query:

java
@Query("select o from Order o left join fetch o.lines where o.id = :id")
Optional<Order> findWithLines(@Param("id") long id);

Join fetching one collection is fine; fetching two collections at once in a single query multiplies rows and raises MultipleBagFetchException, the case handled in fixing MultipleBagFetchException.

An entity graph. For repository methods derived from names, declare what to fetch without writing JPQL:

java
@EntityGraph(attributePaths = {"customer", "lines"})
Optional<Order> findById(Long id);

or as a named graph reusable across methods, see entity graphs in JPA.

Initialising inside the transaction. A last resort for rare cases: touch the association in the service while the transaction is open (Hibernate.initialize(order.getLines())). It issues a second query, and is the least explicit; prefer a fetch join.

Step 4: map to DTOs in the service

Fetching fixes the missing data. The other half of the cure is to stop passing entities out of the transaction at all. A service returns what the caller needs, fully built, and the transaction boundary guarantees it was consistent:

src/main/java/dev/javahacks/orders/OrderService.javajava
@Service
public class OrderService {
    private final OrderRepository orders;

    public OrderService(OrderRepository orders) {
        this.orders = orders;
    }

    @Transactional(readOnly = true)
    public OrderDetails details(long id) {
        Order order = orders.findWithLines(id).orElseThrow(() -> new OrderNotFoundException(id));
        return new OrderDetails(
                order.getId(),
                order.getStatus().name(),
                order.getLines().stream().map(l -> new LineDetails(l.getSku(), l.getQuantity())).toList());
    }
}

The mapping runs inside the transaction, so lazy associations could still be loaded if needed, but with a deliberate fetch there is nothing left to load. The controller receives an immutable OrderDetails record and serialises it. It cannot trigger a query, because it holds no proxies. This is the structure that remains correct if the same service is later called from a scheduled job or a message listener, where Open Session in View never applied.

Step 5: handle the awkward cases

A few patterns need extra thought.

Jackson serialising entities directly. If controllers return entities, Jackson walks their getters, touching lazy associations during serialisation. With the interceptor off these throw. The fix is DTOs; the workaround of the jackson-datatype-hibernate module, which skips uninitialised lazy collections, hides the problem and produces JSON with missing fields. Prefer the real fix.

Templates. A Thymeleaf template with ${order.customer.name} triggers a lazy load during rendering. Pass a view model object that already contains the strings.

Mappers with deep traversal. MapStruct or hand written mappers that map entity graphs are the main source of surprise lazy loads. Map in the service, inside the transaction, after the fetch.

Specifications and paging. A Page<Order> of entities whose mapping touches customer does N plus 1 queries inside the transaction, which now succeeds but is slow. Fetch the association in the query or use a projection; the exception was only hiding the cost before, and now the statistics show it.

Async and event handlers. Handlers that receive an entity from an event and touch associations get no session at all; pass an id or a DTO.

**Tests with @Transactional.** A test method annotated @Transactional keeps a transaction open for its whole body, so lazy loading works in the test where it would fail in production. Tests that exercise the controller through MockMvc are unaffected, since the controller runs in its own flow; tests that call a service and then touch the result in the test body may need @Transactional removed to reveal the same failure real code would see.

Step 6: lock it in with tests

Once the property is off in the test profile, the suite is its own guard. Add targeted tests for the endpoints that used to depend on lazy loading, and one that asserts the query count so an accidental N plus 1 is caught:

java
@SpringBootTest(properties = "spring.jpa.open-in-view=false")
@AutoConfigureMockMvc
class OrderEndpointsWithoutOsivTest {

    @Autowired MockMvc mvc;
    @Autowired EntityManagerFactory emf;

    @Test
    void orderDetailsAreFullyLoadedByTheService() throws Exception {
        mvc.perform(get("/api/orders/1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.lines.length()").value(3));
    }

    @Test
    void listingOrdersDoesNotIssueAQueryPerOrder() throws Exception {
        Statistics stats = emf.unwrap(SessionFactory.class).getStatistics();
        stats.clear();

        mvc.perform(get("/api/orders")).andExpect(status().isOk());

        assertThat(stats.getPrepareStatementCount()).isLessThanOrEqualTo(3);
    }
}

The second test needs hibernate.generate_statistics=true in the test properties and seed data with several orders; its bound is the number of queries you consider acceptable for the endpoint. A budget like this, checked automatically, is the best guard against the problem returning.

Step 7: roll out

Deploy the change with the usual care. Enable the property off in staging for a few days with realistic load; watch the error rate and the logs for LazyInitializationException. Deploy to production with the standard strategy, canary or rolling, and have the rollback be a configuration change, a property flip back to true, which restores the old behaviour immediately. After the rollout, compare against the baselines: connection hold time (hikaricp.connections.usage), the pool's pending count and the per endpoint query counts. The expected result is a lower and steadier connection usage and a few endpoints that now show their true query counts, which you can then optimise, see fixing the N plus 1 problem.

What not to do

**Do not set hibernate.enable_lazy_load_no_trans=true.** This Hibernate property lets lazy loading work outside a transaction by opening a temporary session per access. It restores the "it works" feeling and brings back every cost: a connection per lazy access, queries anywhere, an N plus 1 that is slower than with Open Session in View because each load acquires and releases a connection. It is widely considered an anti pattern.

**Do not make everything FetchType.EAGER.** Eager associations load on every query, whether needed or not, and cascade into huge joins. The default of lazy associations is right; the discipline is to fetch deliberately per use case.

**Do not wrap controllers in @Transactional** to restore the session. It extends transactions over serialisation and view rendering, which holds the connection and locks for the wrong span, the same problem in a different shape.

When this does not apply

If the application is a small server rendered tool with a handful of users, the work may not pay for itself, and keeping the default with an eye on connection use is reasonable. If the service has no JPA, because it uses JDBC or Spring Data JDBC, there is nothing to turn off. For the property's reference documentation see the Spring Boot appendix on common application properties, and for Hibernate's own guidance the Hibernate user guide on fetching.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.