Skip to content

6.5. Transaction Management

6.5.1. @Transactional Usage Rules

  • Transactions must be declared at the Service layer. They must not be declared in Repository or Controller layers.
  • Read-only methods must specify readOnly = true.
java
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

  private final UserRepository userRepository;

  @Override
  @Transactional
  public UserResponse createUser(CreateUserRequest request) {
    UsersRecord record = userRepository.insert(request.name(), request.email());
    return UserResponse.from(record);
  }

  @Override
  @Transactional(readOnly = true)
  public UserResponse findById(Long id) {
    UsersRecord record = userRepository.findById(id)
        .orElseThrow(() -> new UserNotFoundException(id));
    return UserResponse.from(record);
  }
}

6.5.2. Transaction Propagation Rules

Propagation LevelUsage Criteria
REQUIRED (default)General business logic
REQUIRES_NEWWhen an independent transaction is needed (logging, auditing)
SUPPORTSMust not be used
NOT_SUPPORTEDMust not be used

6.5.3. Precautions

  • Calling a @Transactional method from within the same class will not apply AOP proxying.
  • Checked exceptions do not trigger rollback by default. Specify rollbackFor when needed.
java
@Transactional(rollbackFor = Exception.class)
public void processPayment(PaymentRequest request) {
  // ...
}

TIENIPIA QUALIFIED STANDARD