Junior — Middle
In what cases and how is it recommended to use the @Transactional annotation in Spring for transaction management?
sobes.tech AI
Answer from AI
The @Transactional annotation in Spring is used for managing transactions at the method or class level. It ensures that database operations within a method are executed within a single transaction.
It is recommended to apply @Transactional in cases where a method performs multiple related database operations that should be atomic — either all succeed or all are rolled back in case of an error.
Example of usage:
@Service
public class UserService {
@Transactional
public void createUserAndProfile(User user, Profile profile) {
userRepository.save(user);
profileRepository.save(profile);
// If an exception occurs here, both operations will be rolled back
}
}
Important:
- The annotation should be applied to public methods.
- Transactions work correctly when methods are called through Spring proxies.
- You can configure parameters, such as isolation level, behavior on exceptions.