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 Level | Usage Criteria |
|---|---|
REQUIRED (default) | General business logic |
REQUIRES_NEW | When an independent transaction is needed (logging, auditing) |
SUPPORTS | Must not be used |
NOT_SUPPORTED | Must not be used |
6.5.3. Precautions
- Calling a
@Transactionalmethod from within the same class will not apply AOP proxying. - Checked exceptions do not trigger rollback by default. Specify
rollbackForwhen needed.
java
@Transactional(rollbackFor = Exception.class)
public void processPayment(PaymentRequest request) {
// ...
}