Declarative Transaction
Concept
Implemented through @Transactional annotation, automatically managed by Spring AOP.
Usage
@Service
@Transactional(propagation = Propagation.REQUIRED,
isolation = Isolation.DEFAULT,
rollbackFor = Exception.class)
public class TestServiceImpl implements TestService {
// All methods inherit transaction configuration
}
Advantages
- Non-invasive design, business code decoupled from transaction management
- Simple configuration, easy to maintain
- Reduces duplicate code
Disadvantages
- Relatively difficult to debug (transaction boundary is not obvious)
- Strict requirements for exception handling (by default only rolls back RuntimeException)
Programmatic Transaction
Concept
Developers manually write code to manage transactions, implemented through TransactionTemplate or PlatformTransactionManager.
Implementation
@Service
@RequiredArgsConstructor
public class TestServiceImpl implements TestService {
private final TransactionTemplate transactionTemplate;
public String test01() {
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
try {
// Business logic
unitInfoMapper.insertUnitInfo(unitInfo);
} catch (Exception e) {
status.setRollbackOnly(); // Manually mark rollback
}
}
});
return "ok";
}
}
Advantages
- Finer control granularity, high flexibility
- Can precisely control transaction boundaries
- More intuitive debugging
Disadvantages
- High code invasiveness
- Requires writing a lot of template code
Comparison
| Feature | Declarative Transaction | Programmatic Transaction |
|---|---|---|
| Implementation | Based on AOP | TransactionTemplate API |
| Control Granularity | Relatively coarse | Fine |
| Code Invasiveness | Low | High |
Usage Recommendations:
- Declarative transaction: Suitable for most conventional business scenarios
- Programmatic transaction: Suitable for scenarios requiring fine-grained control of transaction boundaries and complex exception handling