Spring - @Transactional - What happens in background?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
When developing applications with Spring Framework that interact with databases, managing transactions is crucial for data integrity and consistency. Spring provides a powerful abstraction for transaction management through its @Transactional annotation, simplifying the development of robust transactional operations. Here, we delve into what happens in the background when you use @Transactional.
Understanding @Transactional
The @Transactional annotation in Spring marks a method or class as transactional, meaning Spring manages the transaction states automatically. When a method annotated with @Transactional is called, Spring ensures that the method executes within a transactional context.
Mechanism of @Transactional
Spring implements the @Transactional functionality using AOP (Aspect-Oriented Programming). Essentially, it creates a proxy around the object where the annotated method is declared. This proxy intercepts calls to the method, and this is where the magic happens.
Here are the steps taken by Spring when a method annotated with @Transactional is executed:
- Check if a transaction is already active: Spring first checks whether there is an ongoing transaction context. If yes, the current method execution joins this transaction.
- Start a new transaction if necessary: If there's no active transaction, Spring starts a new one by obtaining a new database connection and setting the appropriate isolation level, if specified.
- Execute the annotated method: With the transaction set up, the method execution proceeds.
- Commit or roll back the transaction: Upon successful method execution, Spring commits the transaction, making all changes permanent. If an exception is thrown during method execution, Spring rolls back the transaction, preventing any partial data changes.
Propagation and Isolation
Spring handles two important aspects of transactions: propagation and isolation. Propagation defines how transactions relate to each other. For example, PROPAGATION_REQUIRED means use the current transaction or start a new one if none exists. Isolation defines how much one transaction is isolated from changes in other transactions. Common isolation levels include READ_COMMITTED, READ_UNCOMMITTED, etc., which control phenomena like dirty reads, phantom reads, and so forth.
Behind the Scenes with AOP
The AOP proxy surrounding an @Transactional method can be either a JDK dynamic proxy or a CGLIB proxy. The choice depends on whether the target object implements an interface. JDK dynamic proxies are used when the target object implements at least one interface; otherwise, CGLIB is used.
The actual proxy logic is implemented in advice, which is linked to the @Transactional annotation. This advice is responsible for the runtime behavior including starting new transactions, joining existing transactions, exception handling, and more.
Practical Example
Here’s a simple example to illustrate:
In this example, transferMoney is wrapped in a transaction. If any operation inside transferMoney throws an exception, the entire transaction will be rolled back.
Summary Table
Below is a table summarizing key attributes of the @Transactional annotation:
| Attribute | Description | Default |
| propagation | Defines transaction propagation behavior | REQUIRED |
| isolation | Defines the isolation level of the transaction | DEFAULT |
| timeout | Specifies the timeout for the transaction in seconds | -1 (none) |
| readOnly | Marks the transaction as read-only | false |
| rollbackFor | Defines exceptions that trigger rollback | RuntimeException |
Conclusion
Spring's @Transactional provides an abstraction layer that automates transaction management, making database operations less error-prone and easier to maintain. By understanding how it works behind the scenes, developers can better utilize its capabilities and optimize their application’s data handling.
Related reading
- Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace http//www.springframework.org/schema/security
- Spring 5 WebFlux Mono and Flux
- Spring / RabbitMQ transaction management
- Spring Actuator + Kafka Streams - Add kafka stream status to health check endpoint
- Spring actuator's liveness and readiness are returning 404
- Spring aliasFor for Annotations with TargetPARAMETER
- Spring AMQP - Sender and Receiving Messages
- Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.