java / expert
Snippet
Programmatic Transaction Control with TransactionTemplate
While @Transactional is standard, TransactionTemplate offers granular programmatic control within a single method. This is essential when you need to perform multiple distinct operations where only specific blocks require atomicity, or when manual rollback triggers are needed without throwing exceptions.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Servicepublic class CriticalService {private final TransactionTemplate txTemplate;public void executeInSequence() {txTemplate.executeWithoutResult(status -> {repository.save(new Entity("A"));try {externalService.call();} catch (Exception e) {status.setRollbackOnly();}});}}
spring
Breakdown
1
txTemplate.executeWithoutResult(status -> { ... });
Executes the callback code within a managed transaction context.
2
status.setRollbackOnly();
Triggers a rollback manually without needing to rethrow a RuntimeException.
3
private final TransactionTemplate txTemplate;
A thread-safe template that simplifies programmatic transaction management.