← All tutorials

GoCareerGo Tutorials

Spring Boot Tutorial

Auto-configuration, REST APIs, JPA, AOP, caching, microservices and Spring Cloud.

@Transactional

Wraps a method in a database transaction — if an exception is thrown, everything the method did gets rolled back.

@Service
public class TransferService {
    @Transactional
    public void transfer(Long fromId, Long toId, BigDecimal amount) {
        accountRepo.withdraw(fromId, amount);
        accountRepo.deposit(toId, amount); // if this throws, the withdraw rolls back too
    }
}
  • By default, rolls back on unchecked (RuntimeException) exceptions
  • propagation controls how nested @Transactional calls behave (REQUIRED, REQUIRES_NEW...)
  • readOnly = true is a useful hint/optimization for query-only methods