Quick revision
The short answer
We inject a TransactionTemplate, or build one from the PlatformTransactionManager, and pass the database work to its execute() method as a lambda: Order saved = tx.execute(status -> { Order o = repo.save(order); outbox.add(o); return o; }). Only the code inside the lambda runs in the transaction; anything before or after it, such as a remote call, runs without one. For work that returns nothing we use executeWithoutResult(), and we can set propagation, isolation, timeout and readOnly on the template.
What to remember
In this answer, we saw how TransactionTemplate lets us put the transaction boundary around exactly the database work that must be atomic. The callback passed to execute() commits on return and rolls back on a runtime exception, executeWithoutResult() handles void work, setRollbackOnly() undoes work without an exception, and the template carries propagation, isolation, timeout and read-only settings. Code outside the callback, such as remote calls, runs without a transaction and without holding a connection.
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.
We inject a TransactionTemplate, or build one from the PlatformTransactionManager, and pass the database work to its execute() method as a lambda: Order saved = tx.execute(status -> { Order o = repo.save(order); outbox.add(o); return o; }). Only the code inside the lambda runs in the transaction; anything before or after it, such as a remote call, runs without one. For work that returns nothing we use executeWithoutResult(), and we can set propagation, isolation, timeout and readOnly on the template.
Why this question is asked
@Transactional puts the boundary around a whole method, and that is often too wide. A method that calls a payment provider, saves an order and then sends a notification should not hold a database transaction, and a pooled connection, while it waits for the network. Interviewers ask this to see whether we can place the boundary exactly where it belongs. In this answer, we will start from a method that is too wide, rewrite it with TransactionTemplate, look at how the template commits and rolls back, and see how to configure it.
1The Problem: A Transaction That Is Too Wide
Here is a typical service method. The annotation makes the whole method one transaction, so the database connection is borrowed at the first query and held until the method returns, including the two seconds the payment call might take.
With a pool of 10 connections and 3 seconds per order, the service can place only about 3 orders per second before callers start waiting for connections, even though the database work itself takes 20 milliseconds.
2Rewriting It With TransactionTemplate
TransactionTemplate is Spring's programmatic way to run code in a transaction. We give it a callback, a lambda that receives a TransactionStatus. The template starts a transaction, runs the callback, commits if the callback returns normally, and rolls back if it throws a RuntimeException or an Error.
8 messages in order. Play them, or step through them one at a time.
Only the database work sits between begin and commit.
Notice that the order row and the outbox row are still written in one transaction, so they succeed or fail together. That is the part that needs atomicity. The payment call and the email are outside the callback, so they run without a transaction and without a connection. Notice also that the method no longer has @Transactional; if we left it there, the outer transaction would wrap everything again and the template would simply join it.
3Void Work and Manual Rollback
When the callback returns nothing, executeWithoutResult() reads better than returning null. The TransactionStatus parameter also lets us mark the transaction for rollback without throwing, which is useful when we detect a business problem and want to undo the work but still return normally.
A checked exception cannot be thrown from the lambda directly, because TransactionCallback does not declare one. If the work throws a checked exception, we wrap it in a runtime exception inside the callback, which also triggers the rollback.
4Configuring the Template
The template carries the same settings that @Transactional has as attributes. We can set them on a template we create, or declare a configured TransactionTemplate as a bean and inject it. Spring Boot already provides a TransactionTemplate bean with default settings when a single transaction manager exists, so for the default case we can just inject it.
A TransactionTemplate is thread-safe once configured, so one instance can be shared by every thread. If two parts of a class need different settings, we create two templates rather than changing one at runtime.
5Follow-up questions
What happens if the callback calls a method annotated with @Transactional?
With the default REQUIRED propagation, that method joins the transaction the template started, so it all commits or rolls back together. If the inner method uses REQUIRES_NEW, Spring suspends the template's transaction and runs the inner one separately.
Why not move the database part into a separate @Transactional method?
That works too, but only if the method is on another bean, because a call to a method on this skips Spring's proxy and the annotation does nothing. TransactionTemplate avoids that rule and keeps the boundary visible in the same method, which many people find easier to read for short pieces of work.
Is the payment safe if the transaction fails after the charge?
No, and the rewrite makes that visible. If the insert fails after a successful charge, we must refund or record the payment for reconciliation. The original version had the same gap, because a rollback never undid the remote charge either; it only hid the problem behind a wider transaction.
6Conclusion
In this answer, we saw how TransactionTemplate lets us put the transaction boundary around exactly the database work that must be atomic. The callback passed to execute() commits on return and rolls back on a runtime exception, executeWithoutResult() handles void work, setRollbackOnly() undoes work without an exception, and the template carries propagation, isolation, timeout and read-only settings. Code outside the callback, such as remote calls, runs without a transaction and without holding a connection.
Open with
I would remove @Transactional from the method and use TransactionTemplate for just the part that must be atomic. I either inject the TransactionTemplate bean that Spring Boot provides or create one from the PlatformTransactionManager.
Then, if they want more
Then the code is: call the payment provider first, with no transaction, then Order saved = transactionTemplate.execute(status -> { save the order, add the outbox row, return the order }), and after that send the email, again outside the transaction. The template begins the transaction, runs the lambda, commits when it returns, and rolls back on a runtime exception.
If the work returns nothing, executeWithoutResult is cleaner, and status.setRollbackOnly lets me roll back without throwing. I can configure propagation, isolation, timeout and read-only on the template, and since it is thread-safe I can keep one configured instance per kind of work.
The benefit is that the connection is held for the twenty milliseconds of database work, not for the seconds the remote calls take. I would also point out that the payment is outside the transaction, so if the insert fails I need a refund or reconciliation path; a wider transaction never solved that anyway.
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 "Rewrite a method so that only part of it runs in a transaction, using TransactionTemplate.": https://scrivio-interview-library.netlify.app/databases/transactions/e167ceebe1/