Sobes.tech
Junior — Middle

Explain the mechanism of the @Transactional annotation in Spring Framework and how it manages transactions.

sobes.tech AI

Answer from AI

The @Transactional annotation in the Spring Framework is used for managing transactions at the method or class level.

Mechanism of action:

  • When a method annotated with @Transactional is called, Spring creates a proxy that opens a transaction before executing the method.
  • If the method executes successfully, the transaction is committed (changes are saved).
  • If an exception occurs during execution (usually RuntimeException), the transaction is rolled back, undoing all changes.

Thus, @Transactional ensures atomicity of operations, guaranteeing that either all changes within the method are applied or none are saved.

Example:

@Service
public class UserService {

    @Transactional
    public void createUser(User user) {
        userRepository.save(user);
        // other operations that should be in one transaction
    }
}