Junior — Middle
Can you explain the purpose and operation of the @Transactional annotation in the context of database transaction management?
sobes.tech AI
Answer from AI
The @Transactional annotation in Java (commonly in the Spring Framework) is used for managing database transactions at the method or class level.
It provides:
- Automatic start of a transaction when entering the method.
- Automatic commit of the transaction if the method completes successfully.
- Rollback of the transaction in case of exceptions (by default — RuntimeException).
This allows developers not to write manual code for transaction management, increasing reliability and simplifying maintenance.
Example of usage:
@Service
public class UserService {
@Transactional
public void createUser(User user) {
userRepository.save(user);
// other operations that should be atomic
}
}
In this example, if the user is saved successfully, the changes will be committed to the database. If an error occurs, all changes will be rolled back.