0
0
Spring Bootframework~5 mins

Transaction management with @Transactional in Spring Boot

Choose your learning style9 modes available
Introduction

Transaction management helps keep your data safe and consistent. The @Transactional annotation makes sure a group of actions either all happen or none happen.

When saving multiple related records to a database and you want all to succeed or all to fail.
When updating several tables and you want to avoid partial updates.
When deleting data that depends on other data and you want to keep the database consistent.
When calling multiple database operations in one method and you want them treated as one unit.
When you want to automatically rollback changes if an error happens during a process.
Syntax
Spring Boot
@Transactional
public void methodName() {
    // database operations
}

Place @Transactional above methods or classes to manage transactions.

By default, if an exception occurs, the transaction rolls back.

Examples
This method saves a user inside a transaction.
Spring Boot
@Transactional
public void saveUser(User user) {
    userRepository.save(user);
}
This method reads data without allowing changes, improving performance.
Spring Boot
@Transactional(readOnly = true)
public User findUser(Long id) {
    return userRepository.findById(id).orElse(null);
}
This method rolls back the transaction for any exception, checked or unchecked.
Spring Boot
@Transactional(rollbackFor = Exception.class)
public void updateData() throws Exception {
    // multiple database updates
}
Sample Program

This service simulates a money transfer. If the amount is over 1000, it throws an error and rolls back the transaction, so no changes happen.

Spring Boot
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;

@Service
public class BankService {

    private List<String> transactions = new ArrayList<>();

    @Transactional
    public void transferMoney(String fromAccount, String toAccount, int amount) {
        transactions.add("Withdraw " + amount + " from " + fromAccount);
        if (amount > 1000) {
            throw new RuntimeException("Amount too large, rollback transaction");
        }
        transactions.add("Deposit " + amount + " to " + toAccount);
    }

    public List<String> getTransactions() {
        return transactions;
    }
}
OutputSuccess
Important Notes

Use @Transactional on public methods only for it to work properly.

By default, only unchecked exceptions (RuntimeException) cause rollback.

Transactions help keep your data safe when multiple steps must all succeed together.

Summary

@Transactional groups database actions so they all succeed or fail together.

It helps keep data consistent and safe from partial changes.

Use it on methods that do multiple related database operations.