Sobes.tech
Junior — Middle

What is the purpose of the @Transactional annotation in transaction management?

sobes.tech AI

Answer from AI

The @Transactional annotation in Java is used for managing transactions at the method or class level. It allows automatically starting a transaction when entering the method and either committing or rolling it back depending on the execution result. This simplifies working with the database, ensuring data integrity and proper transaction management without the need to write explicit code for beginning and ending transactions.

Example of usage:

@Service
public class UserService {

    @Transactional
    public void createUser(User user) {
        userRepository.save(user);
        // if an exception occurs here, the transaction will be rolled back
    }
}