Junior — Middle
What obligations does the @Transactional annotation fulfill in the context of 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 guarantees the following commitments:
- Atomicity: All operations within a transaction are executed as a single unit — either all succeed or all are rolled back in case of an error.
- Transaction lifecycle management: When entering a method with
@Transactional, a transaction begins; upon successful completion — commit; if an exception occurs — rollback. - Isolation: Ensures a certain level of transaction isolation, preventing issues with concurrent data access.
- Propagation support: Allows defining how the transaction propagates to called methods (e.g., creating a new one or using an existing one).
Example of usage:
@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 createUser method, all changes will be rolled back.