@Transactional in Spring Boot Explained with Real Examples

Transaction management is one of the most important concepts in enterprise application development. Whenever multiple database operations must either succeed together or fail together, transactions become essential.


Spring Boot simplifies transaction management through the @Transactional annotation, allowing developers to focus on business logic rather than low-level database transaction handling.


What is a Transaction?

A transaction is a sequence of operations that must be executed as a single unit of work.

A transaction follows the all-or-nothing principle.



Either All Operations Succeed

OR

All Operations Fail

Real World Example

Consider transferring money between two bank accounts.



Account A
    |
    |
Withdraw 1000
    |
    |
Deposit 1000
    |
    |
Account B

If money is withdrawn from Account A but fails to deposit into Account B, data becomes inconsistent.

A transaction prevents this problem.


Without @Transactional


public void transferMoney() {

    withdraw();

    deposit();

}

If an exception occurs after withdraw(), the database may remain in an invalid state.


Using @Transactional


@Transactional

public void transferMoney() {

    withdraw();

    deposit();

}

Spring manages the transaction automatically.

If an exception occurs, all database changes are rolled back.


ACID Properties of Transactions

All database transactions follow ACID principles.

Atomicity

All operations succeed or fail together.

Consistency

Database remains in a valid state.

Isolation

Transactions do not interfere with each other.

Durability

Committed changes are permanently stored.


Simple Example


@Service
public class EmployeeService {

    @Transactional

    public void saveEmployee() {

        employeeRepository.save(
            employee
        );

    }
}

Spring opens a transaction before execution and commits it after successful completion.


What Happens Internally?


Start Transaction
        |
        v

Execute Business Logic
        |
        v

Success?
   |
   +---- Yes
   |        |
   |        v
   |     Commit
   |
   +---- No
            |
            v
         Rollback

Rollback Example


@Transactional

public void createEmployee() {

    employeeRepository.save(
        employee
    );

    int result =
        10 / 0;

}

ArithmeticException occurs.

Spring rolls back the entire transaction.

Employee is not saved.


Common Interview Trap

Many developers believe every exception triggers rollback.

Actually, Spring rolls back transactions only for unchecked exceptions by default.


Rollback Happens


RuntimeException

NullPointerException

IllegalArgumentException

No Rollback By Default


IOException

SQLException

Checked Exceptions

Forcing Rollback for Checked Exceptions


@Transactional(

    rollbackFor =
    Exception.class

)

Now Spring rolls back for checked exceptions as well.


Transaction Propagation

Propagation determines how transactions behave when one transactional method calls another.


Default Propagation


Propagation.REQUIRED

Join existing transaction if one exists. Otherwise create a new transaction.


Example


@Transactional(
    propagation =
    Propagation.REQUIRED
)

Read Only Transactions

For read operations, transactions can be optimized.



@Transactional(
    readOnly = true
)

This improves performance for database read operations.


Transaction Management Example


@Service
public class BankingService {

    @Transactional

    public void transferFunds(

        Long senderId,

        Long receiverId,

        Double amount

    ) {

        debitAccount(
            senderId,
            amount
        );

        creditAccount(
            receiverId,
            amount
        );

    }

}

Both operations succeed together or fail together.


Common Reasons Why @Transactional Does Not Work

  • Method is private.
  • Method is called internally within same class.
  • No Spring Bean involved.
  • Exception is caught and swallowed.
  • Wrong transaction manager configuration.

Common Interview Questions

What is @Transactional?

It is a Spring annotation that manages database transactions automatically.


What happens if an exception occurs?

Spring performs a rollback for unchecked exceptions.


What are ACID properties?

Atomicity, Consistency, Isolation and Durability.


What is rollback?

Rollback reverses all changes made during a transaction.


Why might @Transactional not work?

Internal method calls and private methods are common causes.


Best Practices

  • Place transaction boundaries in service layer.
  • Keep transactions short.
  • Use readOnly for read operations.
  • Avoid transactions inside controllers.
  • Understand rollback behaviour.

Frequently Asked Questions (FAQ)

Can @Transactional be used at class level?

Yes. It applies to all public methods in the class.


Can a transaction span multiple repository calls?

Yes. This is one of the primary benefits of transaction management.


Does Spring Boot enable transactions automatically?

Yes, when Spring Data JPA is properly configured.


Conclusion

The @Transactional annotation is one of the most powerful features provided by Spring Framework. It ensures data consistency, simplifies transaction management and allows developers to focus on business logic instead of handling commits and rollbacks manually. Understanding transaction behaviour is essential for enterprise development and Spring Boot interviews.


Keywords

@Transactional Spring Boot, Spring Transaction Management, Transaction Rollback, ACID Properties, Spring Data JPA Transactions, Rollback Example, Spring Boot Interview Questions, Transaction Propagation, Read Only Transactions, Spring Framework Transactions, Spring Boot Tutorial, Database Transactions, Java Backend Development, Spring Data JPA, Enterprise Java

@Transactional in Spring Boot Explained with Real Examples @Transactional in Spring Boot Explained with Real Examples Reviewed by 13thGhost on 10:24 AM Rating: 5

Recommended Posts

Powered by Blogger.