Sobes.tech
Junior — Middle

What is the role of the @Transactional annotation in the Spring framework and in which scenarios is it used?

sobes.tech AI

Answer from AI

The @Transactional annotation in Spring is used for managing transactions at the method or class level. It ensures that all operations within the method are executed within a single transaction, which either completes successfully (commit) or is rolled back in case of an error.

Use cases:

  • Database operations where data integrity is important.
  • Service layer methods that combine multiple actions requiring atomicity.

Example:

@Service
public class UserService {

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

If an exception occurs in the method, all changes in the database will be rolled back.

What is the role of the @Transactional annotation in… - sobes.tech