TExcelTAD
Home › Spring Boot › Transactions

Transactions

A transaction groups several database operations into one unit: either all of them succeed (commit) or none of them take effect (rollback). Moving a task to another project, transferring money, creating an order with its items — these must never be left half-done. In Spring you mark the boundary with @Transactional, and the framework begins, commits or rolls back for you.

@Transactional on a service

java
@Service
public class ProjectService {
    private final ProjectRepository projects;
    private final TaskRepository tasks;
    private final AuditLog audit;

    @Transactional
    public void moveTask(long taskId, long targetProjectId) {
        Task task = tasks.findById(taskId).orElseThrow(() -> new TaskNotFoundException(taskId));
        Project target = projects.findById(targetProjectId).orElseThrow();
        if (target.isArchived()) {
            throw new IllegalStateException("Project " + target.getName() + " is archived");
        }
        task.getProject().removeTask(task);
        target.addTask(task);
        audit.record("moved task " + taskId + " to " + targetProjectId);
    }

    @Transactional(readOnly = true)
    public List<ProjectSummary> overview() { ... }
}

If the method returns normally, Spring commits. If it throws a RuntimeException (or an Error), Spring rolls back — every change in the method, including the audit entry, disappears.

The rollback rules

Thrown from the method Default outcome
returns normally commit
RuntimeException (unchecked) rollback
Error rollback
checked Exception (e.g. IOException) commit!

The surprising last row is a historical EJB convention. Change it per method:

java
@Transactional(rollbackFor = Exception.class)          // roll back on checked exceptions too
@Transactional(noRollbackFor = EmailFailedException.class)

Modelling commit and rollback in plain Java

Here is a tiny "database" with transactions, and a proxy-like wrapper that applies Spring's default rules. Watch which changes survive:

java · try it yourself
import java.util.*;

class Database {
    private Map<String, Integer> committed = new TreeMap<>(Map.of("alice", 100, "bob", 20));
    private Map<String, Integer> working;

    void begin() { working = new TreeMap<>(committed); }
    void commit() { committed = working; working = null; }
    void rollback() { working = null; }
    int get(String k) { return working.get(k); }
    void put(String k, int v) { working.put(k, v); }
    Map<String, Integer> snapshot() { return committed; }
}

class InsufficientFundsException extends RuntimeException {
    InsufficientFundsException(String m) { super(m); }
}
class ReceiptException extends Exception {           // checked
    ReceiptException(String m) { super(m); }
}

interface TxWork { void run() throws Exception; }

class TransactionTemplate {
    private final Database db;
    TransactionTemplate(Database db) { this.db = db; }

    void execute(String name, TxWork work) {
        db.begin();
        try {
            work.run();
            db.commit();
            System.out.println(name + ": COMMIT");
        } catch (RuntimeException | Error e) {
            db.rollback();
            System.out.println(name + ": ROLLBACK (" + e.getMessage() + ")");
        } catch (Exception checked) {
            db.commit();                                 // Spring's default for checked exceptions
            System.out.println(name + ": COMMIT despite checked exception (" + checked.getMessage() + ")");
        }
        System.out.println("  balances: " + db.snapshot());
    }
}

class Main {
    static void transfer(Database db, String from, String to, int amount) {
        db.put(from, db.get(from) - amount);
        if (db.get(from) < 0) throw new InsufficientFundsException(from + " cannot pay " + amount);
        db.put(to, db.get(to) + amount);
    }

    public static void main(String[] args) {
        Database db = new Database();
        TransactionTemplate tx = new TransactionTemplate(db);

        tx.execute("transfer 30", () -> transfer(db, "alice", "bob", 30));
        tx.execute("transfer 500", () -> transfer(db, "alice", "bob", 500));
        tx.execute("transfer 10 + receipt", () -> {
            transfer(db, "bob", "alice", 10);
            throw new ReceiptException("printer offline");
        });
    }
}
transfer 30: COMMIT
  balances: {alice=70, bob=50}
transfer 500: ROLLBACK (alice cannot pay 500)
  balances: {alice=70, bob=50}
transfer 10 + receipt: COMMIT despite checked exception (printer offline)
  balances: {alice=80, bob=40}

In the second call, alice's balance had already been reduced in the working copy when the exception was thrown — the rollback discarded that partial change. The third call shows the checked-exception pitfall.

How @Transactional works: proxies

Spring does not modify your class. It wraps the bean in a proxy that starts the transaction, calls your method, and commits or rolls back. That has two important consequences:

  1. Self-invocation is not intercepted. If methodA() calls this.methodB() in the same class, methodB's @Transactional settings are ignored — the call never goes through the proxy.
  2. Only public methods called from outside the bean are reliably transactional (Spring 6 also supports protected and package-private methods with class-based proxies, but public is the convention).
java
@Service
class ReportService {
    public void nightly() {
        generate();          // NOT transactional - bypasses the proxy
    }

    @Transactional
    public void generate() { ... }
}

Propagation

When a transactional method calls another, propagation decides whether they share a transaction:

Propagation Behaviour
REQUIRED (default) join the current transaction, or start one
REQUIRES_NEW suspend the current one and start an independent transaction
MANDATORY must be called inside a transaction, else exception
SUPPORTS join if one exists, otherwise run without
NOT_SUPPORTED suspend any transaction, run without
NEVER fail if a transaction exists

REQUIRES_NEW is useful for audit logs that must be saved even if the main operation rolls back:

java
@Service
class AuditLog {
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void record(String message) { repository.save(new AuditEntry(message)); }
}

Seeing it in the logs

properties
logging.level.org.springframework.orm.jpa.JpaTransactionManager=DEBUG
bash · try it yourself
curl -s -X POST localhost:8080/api/tasks/3/move -H "Content-Type: application/json" -d '{"projectId":9}' -o /dev/null
grep JpaTransactionManager logs/tasks.log | cut -c 120-
: Creating new transaction with name [com.example.tasks.project.ProjectService.moveTask]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
: Opened new EntityManager [SessionImpl(1786311241<open>)] for JPA transaction
: Initiating transaction rollback
: Rolling back JPA transaction on EntityManager [SessionImpl(1786311241<open>)]

Tip: Put @Transactional on service methods that represent one business operation — not on controllers, and not on every repository call. Spring Data repository methods are already transactional individually; your service defines the larger unit.

Test yourself

By default, which exception causes a @Transactional method to roll back?

  1. Any exception
  2. Only checked exceptions
  3. RuntimeException and Error
  4. None; you must call rollback()

Why is @Transactional ignored when a method calls another @Transactional method of the same class via this?

  1. Java forbids it
  2. The call bypasses the Spring proxy that applies the transaction
  3. Only static methods are proxied
  4. Transactions cannot be nested

Which propagation runs a method in its own independent transaction even if the caller has one?

  1. REQUIRED
  2. SUPPORTS
  3. REQUIRES_NEW
  4. MANDATORY