Junior — Middle
What is the impact of using the @Transactional annotation in a Spring application?
sobes.tech AI
Answer from AI
The @Transactional annotation in Spring indicates that a method or class should be executed within a transaction. This means that all database operations within this method will be part of a single transaction, which will either be fully committed or fully rolled back in case of an error.
Main effects of using @Transactional:
- Atomicity: changes are only saved if the entire method succeeds.
- Rollback management: in case of exceptions, the transaction is rolled back.
- Isolation: the transaction isolation level can be configured.
- Propagation management: it can be set how the transaction behaves when calling other transactional methods.
Example:
@Service
public class UserService {
@Transactional
public void createUserAndProfile(User user, Profile profile) {
userRepository.save(user);
profileRepository.save(profile);
// If an exception occurs here, both saves will be rolled back
}
}