Junior — Middle
What is the role of the Transactional annotation in managing transactions in an application?
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 a method and either committing or rolling it back depending on the execution result. This simplifies working with transactions, eliminating the need to manually manage them through the API.
For example, if a method with @Transactional throws an unchecked exception, the transaction is automatically rolled back, ensuring data integrity.
@Service
public class UserService {
@Transactional
public void createUser(User user) {
userRepository.save(user);
// if a RuntimeException occurs here, the transaction will be rolled back
}
}