Quick revision
The short answer
A @DataJpaTest wraps every test in one transaction that stays open until the test ends, so the persistence context is open the whole time and lazy loading always works, while in production the code touches the lazy field after its transaction has closed. The test also rolls back, so inserts that were never flushed never reach the database and constraints are never checked. We fix this by flushing and clearing the EntityManager, testing services with production-like transaction boundaries, and running the tests on the production database engine with Testcontainers.
What to remember
In this answer, we saw that @DataJpaTest keeps one transaction and one persistence context open for the whole test, so lazy loading works where production code runs outside a transaction, and that rollback can discard inserts before they are ever flushed, so constraints are never checked. We fixed the tests by flushing and clearing through TestEntityManager, by testing services without the test transaction so their real boundaries apply, and by running on the production database engine with Testcontainers.
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.
A @DataJpaTest wraps every test in one transaction that stays open until the test ends, so the persistence context is open the whole time and lazy loading always works, while in production the code touches the lazy field after its transaction has closed. The test also rolls back, so inserts that were never flushed never reach the database and constraints are never checked. We fix this by flushing and clearing the EntityManager, testing services with production-like transaction boundaries, and running the tests on the production database engine with Testcontainers.
Why this question is asked
A green test suite and a red production log for the same code is one of the most unsettling things we meet as developers. It usually means the test environment differs from production in a way nobody wrote down. With JPA, the difference is often the test transaction itself. Interviewers ask this question to see whether we understand the persistence context and flush timing well enough to explain the gap, not just patch it. In this answer, we will recap what the persistence context and lazy loading are, see exactly why the test hides each failure, reproduce both, and then fix the tests so they behave like production.
1A Quick Recap: Persistence Context, Lazy Loading and Flush
The persistence context is Hibernate's working memory for one unit of work. It holds every entity we loaded or saved, tracks their changes, and is tied to a transaction in a typical Spring application. When the transaction ends, the persistence context closes.
A lazy association, such as Order.lines mapped with FetchType.LAZY (the default for collections), is not loaded with the order. Hibernate puts a proxy, a placeholder object, in its place and loads the rows the first time we touch it. That only works while the persistence context is open. Touching it later throws LazyInitializationException, because there is no session left to run the query.
Flush is the moment Hibernate sends the queued INSERT, UPDATE and DELETE statements to the database. It happens at commit, before a query that might need the pending changes, or when we call flush() ourselves. Until then, the database has not seen the data and cannot check any constraints.
2Why the Test Hides the LazyInitializationException
@DataJpaTest is annotated with @Transactional. So the TransactionalTestExecutionListener opens a transaction before the test method and keeps it open until the method ends. Every repository call in the test joins it, so they all share one persistence context that stays open for the whole test.
In production, the repository call runs in its own short transaction, or inside a service method's transaction, and returns. The caller, perhaps a controller or a mapper building a response, then reads order.getLines(). The transaction is already closed, so the proxy cannot load, and we get LazyInitializationException. In the test, the same line runs while the test transaction is still open, so the lines load quietly.
| Aspect | @DataJpaTest | Production |
|---|---|---|
| Transaction | one, open for the whole test | one per service or repository call |
| Lazy field read later | loads quietly | LazyInitializationException |
| Saved entity read back | from first-level cache | from the database |
| Pending inserts | rolled back, maybe never flushed | flushed at commit |
| Unique and NOT NULL checks | may never run | run at flush |
| Database engine | often embedded H2 | PostgreSQL or MySQL |
Notice that the test also returns the same Order instance it may have saved earlier in the test, straight from the first-level cache, without reading the database at all. So the test may not even check that the mapping works.
3Why the Test Hides the Constraint Violation
The second problem comes from rollback. The test saves an entity that breaks a unique constraint or leaves a NOT NULL column empty. Hibernate queues the INSERT. The test ends, the listener rolls back, and the queued INSERT is thrown away without ever being sent. The database never had a chance to complain.
In production the same save is followed by a commit, the commit flushes, and the database raises the violation. There is an extra twist: with the default IDENTITY id generation, Hibernate must insert immediately to get the generated key, so some entities do hit the database early and others, with SEQUENCE ids, wait. That makes the test behaviour depend on the id strategy, which is one more reason not to rely on it.
4Fix 1: Flush and Clear in Persistence Tests
The simplest fix is to make the test behave like two separate units of work: write, flush so the SQL runs, clear so the persistence context forgets everything, and then read back from the database. TestEntityManager, which @DataJpaTest provides, has helpers for exactly this.
After clear(), the order is detached, just as it is in production after the transaction ends, so the test now shows the failure. We can then fix the real code, for example with a fetch join or an entity graph in the repository query, and keep this test to prove it.
5Fix 2: Test Services With Production Boundaries
Repository tests check mappings and queries. The LazyInitializationException, though, is about where the service draws its transaction boundary, so it belongs in a service test that does not wrap everything in the test's transaction. We either leave @Transactional off the test class in a @SpringBootTest, or turn the test transaction off for a @DataJpaTest with @Transactional(propagation = Propagation.NOT_SUPPORTED). Now each service call opens and closes its own transaction exactly as in production, and code that touches a lazy field after the service returns fails in the test too. The price is that data is committed, so we clean up after each test.
6Fix 3: Use the Same Database Engine
@DataJpaTest replaces the data source with an embedded database by default. H2 even in compatibility mode differs from PostgreSQL or MySQL in constraint names, deferred constraints, case sensitivity, JSON types and locking. So a constraint that exists only in a Flyway migration written for PostgreSQL may not exist at all in H2. Running the tests against the same engine and the same migrations through Testcontainers, with @ServiceConnection on the container and replace = NONE, removes that whole class of surprises. A PostgreSQL container usually starts in a few seconds and can be shared across test classes.
7Follow-up questions
Should we just enable open-in-view or make the association EAGER?
No. Open-in-view keeps the session open during view rendering and hides the problem in web requests only, at the cost of database work outside the service layer. EAGER loads the lines on every query, even when nobody needs them. It is better to fetch what each use case needs explicitly with a fetch join, an entity graph or a DTO projection.
Does saveAndFlush in the code under test fix the test problem?
It makes that particular insert reach the database during the test, so its constraint is checked, but it changes production behaviour too and does not help with lazy loading. It is better to flush in the test, where the goal is to observe the database, and keep the production code natural.
How do we find these gaps across an existing suite?
Search for repository tests that save and read back in the same test without flush and clear, and for service tests annotated @Transactional. Then switch the test database to the production engine with Testcontainers; the tests that start failing are exactly those that relied on the differences.
8Conclusion
In this answer, we saw that @DataJpaTest keeps one transaction and one persistence context open for the whole test, so lazy loading works where production code runs outside a transaction, and that rollback can discard inserts before they are ever flushed, so constraints are never checked. We fixed the tests by flushing and clearing through TestEntityManager, by testing services without the test transaction so their real boundaries apply, and by running on the production database engine with Testcontainers.
Open with
The test transaction is the difference. DataJpaTest is transactional, so the whole test runs inside one transaction and one persistence context. Lazy associations load fine because the session is still open, and entities I saved often come back from the first-level cache without a real SELECT.
Then, if they want more
In production the repository call ends its transaction, and then a mapper or controller touches a lazy collection, which throws LazyInitializationException. For the constraint violation, the test rolls back at the end, and Hibernate only sends SQL at flush, so if nothing forced a flush, the INSERT never reached the database and the unique or NOT NULL constraint never fired.
In production the commit flushes and the database rejects it. To fix the tests, in repository tests I use TestEntityManager: persistAndFlush so the SQL runs, then clear so I read from the database, and after a clear I can even reproduce the lazy failure.
For services I test without the test transaction, using propagation NOT_SUPPORTED or no Transactional on the class, so the service's own boundaries apply, and I clean up data afterwards. And I run these tests on the same engine and migrations as production with Testcontainers and replace NONE, because H2 can be missing constraints or behave differently.
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 Boot reference, Testing
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 @DataJpaTest passes, but in production the same code fails with a...": https://scrivio-interview-library.netlify.app/spring-boot/spring-boot-test/fa3308e26f/