Spring Framework
Transactional
Programming
Backend Processes
Java

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.

Browse interview questions

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:

  1. 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.
  2. 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.
  3. Execute the annotated method: With the transaction set up, the method execution proceeds.
  4. 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:

java
1import org.springframework.stereotype.Service;
2import org.springframework.transaction.annotation.Transactional;
3
4@Service
5public class BankingService {
6
7    @Transactional
8    public void transferMoney(long sourceAccountId, long targetAccountId, double amount) {
9        accountRepository.deduct(sourceAccountId, amount);
10        accountRepository.add(targetAccountId, amount);
11    }
12}

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:

AttributeDescriptionDefault
propagationDefines transaction propagation behaviorREQUIRED
isolationDefines the isolation level of the transactionDEFAULT
timeoutSpecifies the timeout for the transaction in seconds-1 (none)
readOnlyMarks the transaction as read-onlyfalse
rollbackForDefines exceptions that trigger rollbackRuntimeException

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
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track 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.

Browse interview questions

All Rights Reserved.