Video in progress
When do you choose programmatic transactions with TransactionTemplate over declarative @Transactional?
When the transaction needs to be smaller than a method: only part of a method is in the transaction, committing a big job in chunks, or a place where the proxy doesn't work (self-invocation). With TransactionTemplate the boundary is visible in the code.
📖 Answer
A typical case: call an external API, then write the result to the database.
@Service
class PayoutService {
private final TransactionTemplate tx;
private final BankClient bank;
private final PayoutRepository repo;
PayoutService(PlatformTransactionManager tm, BankClient bank, PayoutRepository repo) {
this.tx = new TransactionTemplate(tm);
this.tx.setTimeout(5); // in seconds
this.bank = bank;
this.repo = repo;
}
void pay(Long id) {
Payout p = tx.execute(s -> repo.markInProgress(id)); // short transaction 1
BankResult r = bank.transfer(p); // outside the transaction
tx.executeWithoutResult(s -> { // short transaction 2
repo.saveResult(id, r);
if (!r.ok()) s.setRollbackOnly();
});
}
}
If the whole pay() method had @Transactional, a DB connection would stay busy while the bank doesn't respond for 10 seconds. Under load the pool runs out.
When TransactionTemplate is better:
- when you don't want a network call inside a transaction: the example above;
- batch processing: committing 1 million rows in separate chunks of 1000, so on an error only that chunk rolls back;
- self-invocation: a
@Transactionalmethod called from within the class doesn't work, while the template doesn't depend on the proxy; - when you need to mix different propagation/isolation within one method.
In ordinary CRUD service methods, @Transactional is better: easy to read, and everyone knows it.
The rollback rule differs: inside the template, RuntimeException and Error cause a rollback, and you can't throw a checked exception out of the lambda in the usual way, so you control the result or setRollbackOnly() explicitly.
Sign up to mark studied questions and save your progress.