Quick revision
The short answer
Spring Boot keeps the Hibernate session open while the view renders (spring.jpa.open-in-view is true by default), so every time the template touches a lazy association such as order.customer or order.lines, Hibernate runs another query. With 500 orders that is the N+1 problem, one query for the list and one or more per row, hidden inside the template. The fix is to load exactly what the page needs in the service with a join fetch, an entity graph or a DTO projection, turn open-in-view off, page the list, and keep template caching on in production.
What to remember
In this answer, we saw that the slow page comes from open session in view, which Spring Boot enables by default and which lets the template trigger a lazy query for each order's customer and lines, the N+1 problem in the view layer. We fixed it by loading exactly what the page needs in the service with an entity graph, a join fetch or a DTO projection, turning spring.jpa.open-in-view off so the mistake fails fast, paging the list, and checking that template caching is on and no expensive expression repeats per row.
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.
Spring Boot keeps the Hibernate session open while the view renders (spring.jpa.open-in-view is true by default), so every time the template touches a lazy association such as order.customer or order.lines, Hibernate runs another query. With 500 orders that is the N+1 problem, one query for the list and one or more per row, hidden inside the template. The fix is to load exactly what the page needs in the service with a join fetch, an entity graph or a DTO projection, turn open-in-view off, page the list, and keep template caching on in production.
Why this question is asked
Slow pages where the controller looks innocent are a classic production puzzle. The controller makes one repository call, the service is fast in a profiler, and yet the request takes three seconds and the SQL log scrolls for a while. Interviewers like this scenario because the answer crosses layers: JPA lazy loading, a Spring Boot default most people never chose, and the template engine. In this answer, we will recap lazy loading and open session in view, reproduce the query storm, then fix it step by step and check the template side as well.
1A Quick Recap of Lazy Loading
In JPA, an association such as Order.customer or Order.lines can be lazy. Hibernate then does not load the related rows with the order. Instead it puts a proxy, a placeholder object, in the field, or an uninitialised collection. The first time code calls a method on it, Hibernate runs a query to load the real data.
That query needs an open session, Hibernate's unit of work with a database connection behind it. Normally the session closes when the @Transactional service method ends, and touching a lazy field after that throws LazyInitializationException. That error is annoying, but it is honest: it tells us we forgot to load something.
2Open Session in View Hides the Problem
Spring Boot registers an interceptor called OpenEntityManagerInViewInterceptor unless we set spring.jpa.open-in-view=false. It opens the session at the start of the web request and closes it only after the view has rendered. Boot even logs a warning at startup that this is enabled by default, because it is so often a surprise.
So the template runs with a live session. Lazy fields no longer throw; they quietly load. Here is what that looks like with our page.
10 messages in order. Play them, or step through them one at a time.
The session stays open during rendering, so each lazy field becomes a query.
Notice that no single line looks expensive. Each query takes maybe 2 to 3 milliseconds, but a thousand of them is two to three seconds, plus the connection is held for the entire render. Under load, that also starves the connection pool, because every page view keeps a connection busy for its whole duration.
3Fix 1: Load What the Page Needs in the Service
The service should hand the view a complete picture. There are three ways, and the right one depends on what the page shows. A join fetch loads associations in the same query. An entity graph does the same declaratively on a repository method. A DTO projection selects only the columns the page needs into a small record, which is often the best choice for a read-only list.
Notice that fetching a collection together with paging is tricky. Hibernate cannot apply LIMIT in SQL when it join-fetches a one-to-many collection, and it warns that it is paging in memory. So for paged lists with collections, either use the projection, or page the order ids first and fetch the lines for those ids in a second query, or set hibernate.default_batch_fetch_size to something like 50, which turns 500 lazy loads into about 10 batched queries.
4Fix 2: Turn Open Session in View Off
Once the service loads everything the page needs, we set spring.jpa.open-in-view=false. Now any lazy field the template still touches throws LazyInitializationException in development, instead of silently costing queries in production. That turns a hidden performance problem into a visible bug, which is exactly what we want.
Turning it off on an existing application can break pages that relied on it, so we do it with tests that render the main pages, and fix each failure by fetching the data in the service. A test that counts statements, for example with Hibernate statistics or a datasource proxy, can also assert that the orders page runs at most two queries.
5Fix 3: Page the List and Check the Template
Even with two queries, rendering 500 rows of HTML is a lot for a person to read and for the browser to draw. A page size of 50 with next and previous links, through a Pageable parameter, keeps the response small and the query fast. If users really need everything, an export to CSV is a better tool than a giant page.
Finally, check the template itself. spring.thymeleaf.cache is true by default and must stay true in production; it is often turned off for development through devtools, and a profile mistake can ship that setting, which makes Thymeleaf parse templates again on every request. Also look for expressions that repeat expensive work per row, such as a method that formats or calculates something inside a th:each loop, and compute it once in the service or the DTO.
- Count SQL statements per requestshow-sql or Hibernate statistics
- Many queries during rendering?Statements logged after the controller returnsYesFetch in the service, open-in-view offNoLook at template and data size
- More rows than a person reads?500 rows on one pageYesAdd paging, offer exportNoKeep the list
- Template cache on?
spring.thymeleaf.cacheYesProfile repeated expressionsNoTurn it on for production
4 steps in order. Play them, or step through them one at a time.
6Follow-up questions
Why does Spring Boot enable open-in-view by default if it causes this?
Because it makes simple applications work without LazyInitializationException, which is friendly for beginners and prototypes. The cost appears with real data volumes and load. Boot logs a warning at startup to make the choice visible, and most production teams set it to false.
What is hibernate.default_batch_fetch_size and when is it enough?
It tells Hibernate to load lazy associations for many parents at once, using an IN list. With a size of 50, touching the lines of 500 orders runs about 10 queries instead of 500. It is a good safety net, but for a known page a projection or an entity graph is still clearer and faster.
How would you stop this from coming back?
Keep open-in-view off so lazy loading in views fails fast, add tests that assert a maximum number of statements for key pages, and watch the queries-per-request metric in production monitoring.
7Conclusion
In this answer, we saw that the slow page comes from open session in view, which Spring Boot enables by default and which lets the template trigger a lazy query for each order's customer and lines, the N+1 problem in the view layer. We fixed it by loading exactly what the page needs in the service with an entity graph, a join fetch or a DTO projection, turning spring.jpa.open-in-view off so the mistake fails fast, paging the list, and checking that template caching is on and no expensive expression repeats per row.
Open with
What's happening is the N+1 problem, just hidden in the view. Spring Boot has spring.jpa.open-in-view set to true by default, so the Hibernate session stays open until the template finishes rendering.
Then, if they want more
The controller loads 500 orders in one query, and then every time Thymeleaf touches order.customer or order.lines, Hibernate quietly runs another query. That's how one page ends up with hundreds or a thousand statements, and it also holds a database connection for the whole render. To fix it, I'd make the service return exactly what the page needs.
For a read-only list, a DTO projection with joins and aggregates is usually best, giving one query plus a count. If the page needs entities, an entity graph or join fetch works, keeping in mind that fetching collections with paging needs care, and batch fetch size is a good safety net.
Then I'd set open-in-view to false, so any remaining lazy access fails in testing instead of costing queries in production. I'd also add paging, because 500 rows on one page isn't useful, maybe 50 per page with an export for bulk needs.
Finally I'd check that spring.thymeleaf.cache is true in production and that no expensive method is called per row inside the loop.
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 Framework reference, Spring Web MVC
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 "A Thymeleaf page listing 500 orders takes 3 seconds to render, and the logs show...": https://scrivio-interview-library.netlify.app/spring-boot/mvc-architecture/e7dbd16318/