Sobes.tech
Junior — Middle

Explain the purpose and working principle of the @Transactional annotation in Spring Framework.

sobes.tech AI

Answer from AI

The @Transactional annotation in the Spring Framework is used for managing transactions at the method or class level. It allows for automatically starting, committing, or rolling back a transaction during the execution of business logic.

How it works:

  • When a method annotated with @Transactional is called, Spring opens a new transaction or joins an existing one.
  • If the method executes successfully, the transaction is committed.
  • If an exception occurs (by default — unchecked), the transaction is rolled back.

This enables developers to avoid writing manual code for transaction management, ensuring atomicity of database operations.

Example:

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