Transactions with @Transactional
Mid-level Always asked 6 min
On this page
The question
Why does a @Transactional method called from the same class not start a transaction? 30-second answer
@Transactional works through a proxy around the bean: callers hold the proxy, which begins and commits around the real method. A self-call is this.save(), which stays inside the object and never crosses the proxy, so no transaction starts, and nothing warns you. Move the method to another bean, so the call goes through a proxy.
Understand it
Self-invocation bypasses the proxy
PredictOrderService has placeOrder, with no annotation, and save, marked @Transactional. placeOrder calls save in the same class. A controller calls placeOrder.
View as text
A caller box, a proxy box and the OrderService object with its two methods. Arrows show the path of the call, and a mark says whether a transaction is active. OrderService has placeOrder, with no annotation, and save, marked @Transactional. placeOrder calls save in the same class. A controller calls placeOrder. The learner first predicts whether save runs in a transaction.
The controller holds a proxy, not your object. placeOrder has no annotation, so the proxy opens nothing and forwards the call.
save(order) means this.save(order). The call stays inside the object and never crosses the proxy, so the annotation is never read. No transaction. The mark reads no transaction.
Called from another bean, the same save goes through the proxy, which opens a transaction. The annotation was fine; the path was not. The caller is now another bean, and the mark reads that a transaction is active.
The fix: move save into another bean, so the call crosses a proxy. Injecting the bean into itself with @Lazy also works, but hides the design problem. A separate bean now holds save, behind its own proxy.
A caller box, a proxy box and the OrderService object with its two methods. Arrows show the path of the call, and a mark says whether a transaction is active. OrderService has placeOrder, with no annotation, and save, marked @Transactional. placeOrder calls save in the same class. A controller calls placeOrder. The learner first predicts whether save runs in a transaction.
The controller holds a proxy, not your object. placeOrder has no annotation, so the proxy opens nothing and forwards the call.
save(order) means this.save(order). The call stays inside the object and never crosses the proxy, so the annotation is never read. No transaction. The mark reads no transaction.
Called from another bean, the same save goes through the proxy, which opens a transaction. The annotation was fine; the path was not. The caller is now another bean, and the mark reads that a transaction is active.
The fix: move save into another bean, so the call crosses a proxy. Injecting the bean into itself with @Lazy also works, but hides the design problem. A separate bean now holds save, behind its own proxy.
Takeaway: @Transactional lives in a proxy around the bean. A call from inside the same object never passes through it, so no transaction starts and nothing warns you.
Propagation modes on a nested call
ExploreREQUIRED joins the outer transaction, or starts one. Nothing is saved. The failure marked the shared transaction rollback-only, so commit throws UnexpectedRollbackException.
View as text
An outer method inserts a row, then calls an inner method that inserts another row. Two boxes show whether each row was saved or rolled back, a line says where the inner method runs, and a mark names any exception that reaches the caller.
REQUIRED joins the outer transaction, or starts one. Nothing is saved. The failure marked the shared transaction rollback-only, so commit throws UnexpectedRollbackException.
REQUIRES_NEW suspends the outer and commits by itself. Only the outer row is saved.
REQUIRES_NEW suspends the outer and commits by itself. Only the inner row is saved.
NESTED uses a savepoint; JpaTransactionManager rejects it. Only the outer row is saved.
MANDATORY demands an existing transaction. Only the outer row is saved. It throws IllegalTransactionStateException.
An outer method inserts a row, then calls an inner method that inserts another row. Two boxes show whether each row was saved or rolled back, a line says where the inner method runs, and a mark names any exception that reaches the caller.
REQUIRED joins the outer transaction, or starts one. Nothing is saved. The failure marked the shared transaction rollback-only, so commit throws UnexpectedRollbackException.
REQUIRES_NEW suspends the outer and commits by itself. Only the outer row is saved.
REQUIRES_NEW suspends the outer and commits by itself. Only the inner row is saved.
NESTED uses a savepoint; JpaTransactionManager rejects it. Only the outer row is saved.
MANDATORY demands an existing transaction. Only the outer row is saved. It throws IllegalTransactionStateException.
Takeaway: Propagation decides whether an inner method shares the caller’s fate. Sharing means one failure rolls back both, even if the caller catches the exception.
In code
@Service
class OrderService {
private final OrderRepository orders;
OrderService(OrderRepository orders) {
this.orders = orders;
}
public void placeOrder(Order order) {
validate(order);
save(order); // this.save(): no transaction
}
@Transactional
public void save(Order order) {
orders.save(order);
orders.audit(order); // not atomic with the line above
}
private void validate(Order order) {
}
}@Service
class PaymentService {
private final AuditLog audit;
PaymentService(AuditLog audit) {
this.audit = audit;
}
// Checked exceptions commit by default: ask for a rollback
@Transactional(rollbackFor = Exception.class)
public void pay(Order order) throws PaymentDeclinedException {
audit.record(order); // commits even if pay rolls back
charge(order);
}
private void charge(Order order) throws PaymentDeclinedException {
}
}
@Component
class AuditLog {
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void record(Order order) {
}
}@Transactional(readOnly = true, timeout = 5)
public List<OrderView> recentOrders() {
return orders.findTop100ByOrderByCreatedAtDesc(); // Hibernate skips dirty checking; slow queries fail after 5 s
}Solve it
Two buyers take the last item: stop the lost update
Stock is 10. Two requests buy one item each at the same moment. Each loads the product, sees 10, writes 9 and commits. The final stock is 9, not 8, though both orders were accepted. Explain and fix it.
- Trace the interleaving. Both transactions read 10 before either writes. The second write overwrites the first: a lost update.
- Know what isolation gives. The default, READ COMMITTED, only hides uncommitted data. It does not stop two read-modify-write cycles from overlapping.
- Pick a fix by contention. For a counter, let the database do the arithmetic in one
UPDATE ... WHERE stock > 0. For whole-entity edits, add@Version: the second commit fails and can retry. - Know the third option.
@Lock(PESSIMISTIC_WRITE)reads withSELECT ... FOR UPDATE, so the second buyer waits. It is simple, but it holds locks and can deadlock. - Check. A test runs two buyers on two threads: stock ends at 8, or one buyer gets a clear “out of stock”.
interface ProductRepository extends JpaRepository<Product, Long> {
@Modifying
@Query("update Product p set p.stock = p.stock - 1 where p.id = :id and p.stock > 0")
int takeOne(long id); // 1 row updated, or 0 when sold out
}
@Transactional
public void buy(long productId) {
if (products.takeOne(productId) == 0) throw new OutOfStockException(productId);
}
@Entity
class Product {
@Id Long id;
int stock;
@Version long version; // a stale write throws OptimisticLockingFailureException
}How to answer
- It applies to any proxy-based feature, such as
@Asyncand@Cacheable. - Injecting the bean into itself with
@Lazyworks, but hides a design problem. TransactionTemplategives a transaction with no proxy involved.- AspectJ weaving removes the limit, at the cost of a build or load-time step.
Common mistakes
- Saying the annotation itself starts the transaction.
- Not knowing the limit exists, then blaming the database for partial writes.
Follow-up questions
What are transaction propagation and isolation?
Propagation says what a method does when a transaction may already exist. REQUIRED, the default, joins it or starts one, and REQUIRES_NEW suspends it and runs its own. Isolation says what a transaction can see of others: READ_COMMITTED prevents dirty reads, REPEATABLE_READ also non-repeatable reads, and SERIALIZABLE phantoms too. The database enforces isolation.
- The default isolation is the database's own, often
READ_COMMITTED. NESTEDuses a savepoint, andJpaTransactionManagerrejects it by default.REQUIRES_NEWholds a second connection, and can exhaust the pool under load.- Stronger isolation costs throughput, through locks or retries.
See it in the infographic: Propagation modes on a nested call
Which exceptions roll a transaction back?
By default, RuntimeException and Error roll back, and a checked exception commits. Change that with rollbackFor and noRollbackFor. A catch inside the method means the proxy sees no exception, so it commits. To roll back after catching, rethrow or call setRollbackOnly().
- A checked exception committing is the classic surprise.
- The rule comes from EJB (Enterprise JavaBeans), where checked meant a recoverable business outcome.
- Catching an exception hides it from the proxy.
@Transactional(rollbackFor = Exception.class)
public void pay(Order order) throws PaymentDeclinedException {
orders.save(order);
gateway.charge(order); // a checked exception now rolls back
} See it in the infographic: Self-invocation bypasses the proxy See it in the infographic: Propagation modes on a nested call
An inner @Transactional method throws, the outer method catches it, and you still get UnexpectedRollbackException. Why?
With REQUIRED, inner and outer share one transaction. When the exception crosses the inner proxy, it marks that transaction rollback-only. The outer method catches the exception and returns normally, so the proxy tries to commit, finds the mark, rolls back, and throws. Use REQUIRES_NEW or NESTED if the inner failure really is optional.
- The mark is set at the proxy boundary, so catching it later is too late.
- Calling a private helper does not set a mark, because no proxy is crossed.
- Both rows are gone, and the exception reaches the caller.
See it in the infographic: Propagation modes on a nested call
When would you use REQUIRES_NEW, and what can go wrong?
Use it for work that must survive the caller's rollback, such as an audit record: its row stays even when the outer method throws. It suspends the outer transaction and takes a second connection, so the outer's connection sits idle, and a pool can deadlock under load. The inner cannot see the outer's uncommitted rows, and can block on its locks.
- A small pool plus
REQUIRES_NEWper request can exhaust connections. - An outbox or an event after commit is often a better design.
@TransactionalEventListenerruns work after the commit succeeds.
See it in the infographic: Propagation modes on a nested call
Where should @Transactional go, and how long should a transaction last?
Put it on the service method that defines one unit of business work, not on controllers or on each repository call. Keep it short: a transaction holds a database connection and locks, so a slow HTTP call inside one can exhaust the pool. Do remote calls before or after it. Mark read-only work with readOnly = true.
readOnly = truelets Hibernate skip dirty checking, and can route reads to a replica.- A remote call cannot be rolled back with the database.
timeoutlimits how long a transaction may run.
See it in the infographic: Self-invocation bypasses the proxy
Can @Transactional go on a private method?
It has no effect there, because a proxy cannot override a private method. Since Spring Framework 6, class-based proxies do handle protected and package-private methods. A final method is also not intercepted. There is no error in any of these cases, only a method that runs with no transaction.
Does a transaction follow work to a new thread?
No. The transaction is bound to the current thread through a ThreadLocal, so a thread started inside a transaction sees none active. @Async work, parallel streams and executors each run outside the caller's transaction, and may read data the caller has not committed yet.
How can a test prove a transaction is active?
Call TransactionSynchronizationManager.isActualTransactionActive() inside the method. Or test the outcome: make the second write fail, then assert the first one rolled back. Beware a test class with @Transactional, because its transaction hides this bug, since the code joins it.
Check yourself
Show answers
- No transaction starts.: Correct. The self-call never crosses the proxy, so nothing reads the annotation.
- A transaction starts at the annotated method.: Incorrect. That only happens when the call comes through the proxy, from another bean.
- Spring throws at run time.: Incorrect. Nothing fails, which is why this bug survives until production.
Show answers
- It is committed.: Correct. Only RuntimeException and Error roll back by default. Use rollbackFor to change that.
- It is rolled back.: Incorrect. That is the default for unchecked exceptions only.
- It stays pending until the caller decides.: Incorrect. The proxy ends the transaction as the method exits, either way.
Show answers
- Only the inner row: Correct. The inner transaction already committed by itself. Only the outer transaction rolls back.
- Neither: Incorrect. That is what happens with REQUIRED, where both share one transaction.
- Both: Incorrect. The outer transaction does roll back, so its row is gone.