Senior
How does the @Transactional annotation work in Spring? How is it implemented within the framework?
sobes.tech AI
Answer from AI
The @Transactional annotation in Spring is used for declarative transaction management. It allows for automatically starting, committing, or rolling back a transaction around a method.
Within Spring, this is implemented using AOP (Aspect-Oriented Programming):
- When a method annotated with
@Transactionalis called, a proxy is created that wraps the call. - The proxy begins a transaction via
PlatformTransactionManagerbefore executing the method. - If the method completes without exceptions, the transaction is committed.
- If an exception occurs (by default RuntimeException), the transaction is rolled back.
Example:
@Service
public class UserService {
@Transactional
public void createUser(User user) {
userRepository.save(user);
// other operations that should be atomic
}
}
Thus, developers do not need to manually manage transactions — Spring takes care of it, ensuring data consistency and simplifying the code.