Quick revision
The short answer
I would point out that both approaches hide the data access pattern: scattered Hibernate.initialize calls and open-in-view both load associations one at a time, often as extra queries or N+1, far from where anyone can see them. Instead, each use case should have its fetch plan at the repository level with entity graphs or fetch joins, services should return DTOs so the web layer never touches lazy associations, OSIV should be disabled with the failures it reveals fixed by tests, and statement-count tests should keep the fixed paths efficient.
What to remember
In this answer, we saw that scattered Hibernate.initialize calls and open session in view both hide data access, producing extra queries and N+1 far from the repository. The recommendation is to define fetch plans per use case in the repository with entity graphs or fetch joins, return DTOs from services, disable OSIV and fix the failures the tests reveal, and add statement-count tests to keep the fixed paths efficient.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
I would point out that both approaches hide the data access pattern: scattered Hibernate.initialize calls and open-in-view both load associations one at a time, often as extra queries or N+1, far from where anyone can see them. Instead, each use case should have its fetch plan at the repository level with entity graphs or fetch joins, services should return DTOs so the web layer never touches lazy associations, OSIV should be disabled with the failures it reveals fixed by tests, and statement-count tests should keep the fixed paths efficient.
Why this question is asked
Code review is where a team's habits become visible. When a reviewer sees Hibernate.initialize(order.getLines()) in five service methods and spring.jpa.open-in-view=true in the configuration, it tells a story: at some point LazyInitializationException appeared, and each developer found a local way to make it disappear. Interviewers ask this scenario to see whether we can explain why the workarounds hurt and propose a direction the team can actually follow. In this answer, we will see what each workaround does, why both are problems, and then the recommendation step by step, with code for the target shape.
1What the Two Workarounds Do
Hibernate.initialize(x) forces a lazy proxy or collection to load immediately, while the session is still open. Called on order.getLines(), it runs select ... from order_line where order_id = ? right there. It does work, in the sense that the lines are then available after the transaction ends.
spring.jpa.open-in-view=true, open session in view or OSIV, registers an interceptor that opens the persistence context at the start of each web request and closes it only when the response has been written. Lazy associations accessed in controllers, view templates or during JSON serialization can then still load. In Spring Boot it is enabled by default, and Boot logs a warning at startup when the property is not set explicitly, precisely because it has these side effects.
2Why Both Hide the Data Access Pattern
With Hibernate.initialize in a service, the query is a side effect of a method call that looks like it does nothing. A loop over 100 orders calling Hibernate.initialize(order.getLines()) runs 100 queries, an N+1 written by hand. Nobody reading the repository can see what the use case loads, because the loading is spread across service code, and each new caller adds its own initialize calls.
With OSIV, the queries move even further away, into the web layer. Jackson walks the entity and triggers lazy loads one by one, so a response with 50 orders and their customers runs 51 queries during serialization, and no service code mentions them. OSIV also keeps a database connection for the whole request, including time spent rendering and writing the response, which reduces how many requests the connection pool can serve. And writes made after the service returned are not in any transaction.
8 messages in order. Play them, or step through them one at a time.
The service looks like one query; the response actually costs 51.
3Recommendation 1: Fetch Plans per Use Case in the Repository
The first recommendation is to make loading explicit. Each use case gets a repository method that loads exactly what it needs, with an entity graph or a fetch join, and its name says so. Hibernate.initialize calls disappear because the data is already there.
Notice that the fetch plan now lives next to the query, where a reviewer can read it, and the list case becomes one query instead of one per order.
4Recommendation 2: Services Return DTOs
The second recommendation is that services return DTOs, plain records shaped for the caller, built inside the transaction. Then the web layer only ever sees fully loaded, simple objects, and nothing it does can trigger a query. It also stops entities' internal fields from leaking into the API, and makes the JSON shape independent of the mapping.
For read-only lists, a projection query that selects the three columns straight into OrderSummary is cheaper still, because no entities are created or tracked.
5Recommendation 3: Disable OSIV and Let the Tests Find the Gaps
With fetch plans and DTOs in place, OSIV is no longer needed, so we set spring.jpa.open-in-view=false. That will make some endpoints fail with LazyInitializationException, and that is useful: each failure points at a use case whose fetch plan is missing. Running the integration test suite with OSIV disabled lists them; we fix each one with a repository method and a DTO, not with a new Hibernate.initialize. For a large codebase, we can do it module by module, starting with the endpoints that have the most traffic.
- Add statement-count testsbaseline for key endpoints
- Move fetching into repository methodsentity graphs, fetch joins
- Return DTOs from servicesbuilt inside the transaction
- Set open-in-view=falsein tests first, then per service
- Failures found?YesAdd the missing fetch planNoRelease
- Keep the count testsguard against regressions
6 steps in order. Play them, or step through them one at a time.
6Recommendation 4: Guard the Fixed Paths With Statement Counts
Finally, once a path is efficient, a test keeps it that way. A statement-count test runs the use case against a real database with enough rows, say 20 orders with different customers, and asserts the number of statements, using Hibernate statistics or datasource-proxy. If someone later adds an association to the DTO without updating the fetch plan, the count rises from 1 to 21 and the build fails, long before production.
In the review itself, I would phrase all this as a direction for the team rather than a list of objections to the pull request: approve the immediate fix if it is urgent, and open a short design note that explains the target shape with these examples.
7Follow-up questions
Is Hibernate.initialize ever the right tool?
Occasionally, inside a transaction, for one association on one entity in code that cannot easily change its query, for example inside a library. It is a legitimate API. The problem is using it as the general answer, especially in loops, where it becomes a hand-written N+1.
What breaks when OSIV is turned off besides controllers?
View templates such as Thymeleaf that navigate associations, exception handlers that log entity details, and security checks that read lazy associations of the current user. The integration tests and the startup of each page under test reveal them.
Why is holding a connection for the whole request a problem?
The pool has a fixed number of connections, for example 10. If each request holds one while rendering and writing a large response, throughput drops and under load requests wait for connections. Without OSIV, the connection is returned as soon as the transaction ends.
8Conclusion
In this answer, we saw that scattered Hibernate.initialize calls and open session in view both hide data access, producing extra queries and N+1 far from the repository. The recommendation is to define fetch plans per use case in the repository with entity graphs or fetch joins, return DTOs from services, disable OSIV and fix the failures the tests reveal, and add statement-count tests to keep the fixed paths efficient.
Open with
I would say that both patterns solve the symptom, LazyInitializationException, by hiding where data is loaded. Hibernate.initialize in services runs a query as a side effect, and in a loop it is a hand-written N+1; nobody reading the repository can see what a use case loads.
Then, if they want more
OSIV keeps the session open for the whole request, so lazy loads move into controllers and JSON serialization, often as N+1 during rendering, and each request holds a database connection until the response is written, which hurts throughput. Spring Boot even warns about it at startup. My recommendation has four parts.
First, define the fetch plan per use case at the repository level, with entity graphs or fetch joins, in methods whose names say what they load, so the Hibernate.initialize calls go away. Second, have services return DTOs built inside the transaction, so the web layer never touches lazy associations and the API does not expose entities.
Third, set open-in-view to false, run the integration tests, and fix every LazyInitializationException they reveal with a fetch plan, not with initialize. Fourth, add statement-count tests on the key endpoints so the fixed paths stay efficient. In the review, I would approve an urgent fix if needed and write a short design note with the target shape.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "During code review you see Hibernate.initialize(order.getLines()) calls sprinkled in...": https://scrivio-interview-library.netlify.app/databases/jpa-performance/3f791438e0/