Junior — Middle
Have you had experience using the @Transactional annotation in your projects?
sobes.tech AI
Answer from AI
The @Transactional annotation in Java is used for managing transactions at the method or class level. It ensures that all operations within the method are executed as a single unit: either all succeed (commit) or, in case of an error, are rolled back (rollback).
Example of usage:
@Service
public class UserService {
@Transactional
public void createUserAndAccount(User user, Account account) {
userRepository.save(user);
accountRepository.save(account);
// If an exception occurs here, both operations will be rolled back
}
}
Thus, @Transactional helps ensure data integrity and simplifies transaction management.