Senior
How does the @Transactional annotation work? How is transactional logic added?
sobes.tech AI
Answer from AI
The @Transactional annotation in Java (for example, in the Spring Framework) is used to designate methods or classes that should be executed within a transaction.
How it works:
- When a method annotated with
@Transactionalis called, Spring creates a proxy object that wraps the method call. - The proxy begins a transaction (via a transaction manager, such as
PlatformTransactionManager) when the method is invoked. - If the method executes successfully, the transaction is committed.
- If an exception occurs, the transaction is rolled back.
Transactional logic is added through dynamic proxying (using JDK Proxy or CGLIB), which allows injecting additional behavior around the method call without changing its code.
Example:
@Service
public class MyService {
@Transactional
public void updateData() {
// database operations
}
}
Here, updateData will be executed within a transaction automatically managed by Spring.