Disable request-wide persistence access and fetch or project the data needed before the service returns.
Spring Boot Open EntityManager in View: close the response-time query gap
A serializer can become a query caller
A controller returns a JPA entity. After the service transaction ends, JSON serialization touches a lazy association. With Open EntityManager in View enabled, that traversal can issue SQL during response rendering, outside the deliberate service read plan. With it disabled, the missing fetch becomes visible as a lazy-loading failure. Prefer a DTO whose fields were assembled inside a bounded service transaction. A to-one graph or a projection can supply the required fields.
Choose one read boundary
Set spring.jpa.open-in-view=false in application configuration, then identify endpoints that returned entities. Move mapping into the service and make the required associations explicit. Do not respond by turning every relationship eager; that expands unrelated queries and can multiply rows on collections. A read-only service method states intent, while the hint alone does not pick the correct fetch plan.
Test serialization end to end
Run a real HTTP test with SQL statement counting. Assert that serialization performs no unexpected database queries and that the response stays correct after the service transaction closes. An endpoint that needs 47 records should not accidentally make 47 association round trips. Watch connection hold time and response latency before and after the change; disabling Open EntityManager in View exposes assumptions that must be repaired endpoint by endpoint.
Implementation contract
spring.jpa.open-in-view=falseCost and verification
Closing the request-wide persistence context avoids late SQL and may shorten connection use. Deliberate DTO mapping can add code and additional targeted queries; count those queries instead of assuming the configuration alone improves latency.
Common Mistakes
- Do not return a JPA entity as an HTTP response and rely on serialization to choose its fetch plan.
- Do not fix a lazy-loading failure by making every association eager.
- Do not assume switching the property repairs existing endpoints without response-level tests.
Read next
Spring Data JPA entity graph for a bounded to-one read, Spring Data JPA projections: return selected fields without a full entity, Spring read-only transaction: performance hint, not a write guard, Spring JPA fetch plans: measure N+1 queries before changing mappings, Spring Data JPA Page versus Slice: pay for totals only when needed.
