Quick revision
The short answer
Spring's TransactionalTestExecutionListener starts a transaction before each @Transactional test method and rolls it back afterwards, so everything the test wrote through that transaction disappears. With RANDOM_PORT, the request is handled by a real server on another thread with its own transaction, which commits normally and is not part of the test's transaction, so that data stays and the test must clean it up itself.
What to remember
In this answer, we saw that the TransactionalTestExecutionListener starts a transaction on the test thread before each @Transactional test and rolls it back afterwards, and that @Commit, @Rollback(false) and TestTransaction change this. Because Spring binds transactions to threads, a RANDOM_PORT request handled on a server thread runs in its own transaction and commits, so the test must clean up. We also saw that rollback can hide flush-time errors, and that calling flush() makes the database check the data before the test ends.
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's TransactionalTestExecutionListener starts a transaction before each @Transactional test method and rolls it back afterwards, so everything the test wrote through that transaction disappears. With RANDOM_PORT, the request is handled by a real server on another thread with its own transaction, which commits normally and is not part of the test's transaction, so that data stays and the test must clean it up itself.
Why this question is asked
Rollback after each test is one of the most convenient features of Spring's test support: every test starts from the same clean data without any cleanup code. But it also causes confusion, because it only works in some kinds of tests, and it can hide errors that would appear in production. Interviewers ask this to check that we understand where a transaction lives and which code runs inside it. In this answer, we will recap how a Spring transaction is tied to a thread, see how the test framework starts and rolls back its transaction, look at the ways to change that, explain why a RANDOM_PORT test does not see the rollback, and finish with the flush problem that rollback can hide.
1A Quick Recap: Transactions Belong to a Thread
A transaction groups database changes so they commit or roll back together. In Spring, the transaction manager keeps the current transaction and its database connection in a ThreadLocal, a variable that has a separate value for every thread. When code on the same thread asks for a connection, for example a repository called from a @Transactional service, it gets the same connection and joins the same transaction.
So the important question for any test is: which thread runs the code that writes the data? If it is the test's own thread, the code can join the test's transaction. If it is another thread, it cannot, whatever annotations we use.
2How the Test Framework Rolls Back
The Spring TestContext framework runs a set of listeners around every test method. One of them, the TransactionalTestExecutionListener, checks whether the test method or class is annotated with @Transactional. If it is, the listener asks the transaction manager to start a transaction before the method runs, on the test thread, and after the method finishes it rolls the transaction back. Rollback is the default for test-managed transactions, which is the opposite of production code.
6 messages in order. Play them, or step through them one at a time.
Only work done on the test thread is rolled back; the server thread already committed.
Notice that repo.save joins the test transaction because it runs on the same thread. When the method ends, the listener rolls back and the row never existed as far as other tests are concerned. The same applies to @DataJpaTest, which is itself annotated with @Transactional, and to MockMvc in the default MOCK web environment, because MockMvc calls the controller on the test thread.
3Changing the Default: @Commit, @Rollback and TestTransaction
Sometimes we want a test to commit, for example to prepare data for a check that runs outside the transaction. @Commit, or its equivalent @Rollback(false), on a method or class tells the listener to commit instead of rolling back. For finer control inside one test, the TestTransaction class lets us end the current test transaction and start a new one.
This is useful for testing code that runs only after commit, such as @TransactionalEventListener handlers. The cost is that committed data stays in the database, so the test must clean it up, exactly like a RANDOM_PORT test.
4Why RANDOM_PORT Does Not Roll Back
With webEnvironment = RANDOM_PORT, Spring Boot starts a real embedded server, Tomcat for example, on a free port. The test calls it with TestRestTemplate, WebTestClient or RestClient over a real HTTP connection. The request arrives on one of the server's worker threads, not on the test thread.
That server thread has no test transaction in its ThreadLocal. When the controller calls a @Transactional service, Spring starts a brand new transaction on the server thread and commits it when the service returns. By the time the test receives the 201 response, the row is committed. The listener later rolls back the test thread's transaction, but that transaction never contained the insert, so the row stays.
So the @Transactional on this class gives a false sense of safety. The fix is explicit cleanup: delete the rows in an @AfterEach method, truncate the tables with a @Sql script, or give each test its own data, such as unique customer names, so leftovers do not matter. Many teams drop @Transactional on RANDOM_PORT tests entirely, so nobody expects a rollback.
5The Hidden Cost: Errors That Wait for Flush
There is one more trap. JPA and Hibernate do not send SQL the moment we call save or persist. They queue the change in the persistence context and send it at flush time, which normally happens at commit or before a query that needs it. In a test that rolls back, there may be no commit, so some SQL is never sent, and errors that only the database can raise, such as a unique constraint or a NOT NULL column, never happen.
So in tests that check persistence behaviour, we call flush(), or use saveAndFlush or TestEntityManager.persistAndFlush, to force the SQL to run before the test ends. The exact exception type depends on whether the call goes through a Spring repository proxy, which translates it, so check what your code sees.
6Follow-up questions
Does MockMvc see the rollback?
Yes, in the default MOCK web environment. MockMvc does not open a socket; it calls the DispatcherServlet directly on the test thread, so the controller and services join the test transaction and their changes are rolled back. That is one reason MockMvc tests are often simpler to keep isolated than RANDOM_PORT tests.
Can I make the server thread join the test transaction?
Not in a supported way. The transaction is bound to the test thread and its connection, and a request on another thread uses another connection from the pool. Trying to share it would also make the test unlike production, where every request has its own transaction. Clean up explicitly instead.
Does code started with @Async inside a @Transactional test get rolled back?
No, for the same reason as RANDOM_PORT. @Async runs the method on an executor thread, which has no test transaction, so its writes commit on their own. Tests of asynchronous code need explicit cleanup and usually a wait for the work to finish.
7Conclusion
In this answer, we saw that the TransactionalTestExecutionListener starts a transaction on the test thread before each @Transactional test and rolls it back afterwards, and that @Commit, @Rollback(false) and TestTransaction change this. Because Spring binds transactions to threads, a RANDOM_PORT request handled on a server thread runs in its own transaction and commits, so the test must clean up. We also saw that rollback can hide flush-time errors, and that calling flush() makes the database check the data before the test ends.
Open with
When a test class or method is annotated with @Transactional, the TransactionalTestExecutionListener from the Spring TestContext framework starts a transaction before the test method, on the test thread, and rolls it back after the method.
Then, if they want more
Spring keeps the current transaction in a ThreadLocal, so repositories and services called from the test on that thread join it, and everything they wrote disappears. If I want the data committed, I use @Commit or @Rollback(false), and inside a test I can use TestTransaction.flagForCommit, end and start, which is handy for after-commit listeners. With RANDOM_PORT the picture changes.
Spring Boot starts a real server and my test calls it over HTTP, so the request runs on a Tomcat worker thread. That thread has no test transaction, so the service starts its own and commits it before the response comes back.
The test's rollback only covers the test thread, so the data stays, and I have to clean up with an AfterEach, a SQL script, or unique test data. One more thing I watch for is that rollback can hide errors: JPA only sends SQL at flush, so a constraint violation may never reach the database.
In persistence tests I call flush or saveAndFlush so the database actually checks the data.
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 "In a Spring test annotated with @Transactional, data inserted in the test is rolled back...": https://scrivio-interview-library.netlify.app/spring-boot/spring-boot-test/b5aaf5e9d1/