Transactions

Key idea
A transaction groups several operations into one atomic unit: either all of them are committed or none. In Spring you declare it with `@Transactional`; a proxy begins the transaction through the `PlatformTransactionManager`, calls your method and commits, or rolls back if an unchecked exception comes out.
In the box
Renewing a box membership is two writes, extending the membership and charging the wallet, and they go together or not at all. Let @Transactional begin, commit and roll back for you, and learn which exceptions roll back, which attributes it has and how to test it.
AthleteRenewalControllerManualTxRenewalServicePlatformTransactionManagerH2

The controller calls renew() on ManualTxRenewalService, highlighted in red, which asks the transaction manager, connected to the database, for getTransaction().

The transaction manager, highlighted, sends setAutoCommit(false) to the database. Above, the controller, proxy and RenewalService flow; below, the two repositories.

The RenewalService proxy and the service itself, highlighted: the service now contains only the two writes.

Packets travel the flow: renew(Leo) to the proxy, BEGIN to the manager, extend() to the membership repository and a failed debit() to the wallet one; finally ROLLBACK goes back to the manager. The proxy and WalletRepository are highlighted.

RenewalService, highlighted, has thrown a checked exception and still the COMMIT packet reaches the manager.

The proxy and the manager, highlighted, exchange the transaction's readOnly and isolation attributes.

TransactionTemplate, highlighted in place of the proxy, sends execute() to the manager and setRollbackOnly() towards the service.

Only the manager, the repositories and the database remain; the manager, highlighted, sends ROLLBACK after test to the database.

Final view: controller, proxy and RenewalService on top; the transaction manager and the two repositories below, connected to the database.

Step 1 of 9

Two writes that go together

Renewing Leo's membership is two writes: add months to his membership and subtract the price from his wallet. If the second one fails (not enough balance), the first one can't stay.

ManualTxRenewalService solves it by hand: it asks the PlatformTransactionManager for a transaction, does both writes, commits and, if anything fails, rolls back.

Step 2 of 9

PlatformTransactionManager: the abstraction

Spring separates what you want (a transaction) from how each technology does it. The piece is PlatformTransactionManager, with an implementation for each case:

  • DataSourceTransactionManager / JdbcTransactionManager: JDBC (what this example uses).
  • JpaTransactionManager: JPA/Hibernate.
  • JtaTransactionManager: distributed transactions (JTA).

The manager turns off the connection's auto-commit, binds it to the current thread (so JdbcTemplate and the repositories use the same one) and at the end calls commit or rollback.

Step 3 of 9

@Transactional: declarative

With @Transactional on renew(), the service keeps only its logic. The rest is done by a proxy (the same mechanism as in the AOP lesson):

  1. The controller calls renew() on the proxy.
  2. The proxy asks the manager to begin a transaction.
  3. It calls your method.
  4. If it completes, commit; if it throws a RuntimeException or an Error, rollback.

@Transactional works on a method or on the class (applying to all its public methods); if both have it, the method one wins.

Step 4 of 9

A renewal without enough money

Leo has €50 and tries to renew one month (€79):

  1. The proxy begins the transaction (BEGIN).
  2. extend() adds a month to his membership.
  3. debit() doesn't find enough balance and throws InsufficientFundsException, a RuntimeException.
  4. The proxy sees the exception and rolls back: the added month disappears.

The test checks it: the exception reaches the caller, and the membership is still at 0 months and the wallet at €50.

Step 5 of 9

Trap: checked exceptions commit

renewWithInvoice() does both writes and then throws InvoiceException, a checked exception. Rollback?

No. The default rule (inherited from EJB) is:

  • RuntimeException and Error → rollback.
  • Checked exceptions → commit whatever was done.

The test confirms Ana has one more month and €79 less, even though the method threw an exception. To change it, @Transactional(rollbackFor = InvoiceException.class), which you'll see in the next lesson.

Step 6 of 9

readOnly, isolation, timeout

@Transactional has attributes to tune the transaction:

  • readOnly = true: a hint that there will be no writes. The manager and the driver can optimise (Hibernate skips dirty checking), but it isn't a guaranteed ban.
  • isolation: what concurrent transactions can see. READ_UNCOMMITTED (allows dirty reads), READ_COMMITTED (prevents dirty ones), REPEATABLE_READ (also prevents non-repeatable ones), SERIALIZABLE (also prevents phantoms). DEFAULT uses the database's.
  • timeout: seconds before the transaction is rolled back.
  • propagation, rollbackFor and noRollbackFor: in the next lesson.

Step 7 of 9

TransactionTemplate: programmatic

Sometimes you want the transaction around a specific piece of code, or to decide on rollback without throwing. That's what TransactionTemplate is for (Spring Boot auto-configures it):

  • tx.execute(status -> { … }) begins the transaction, runs the lambda and commits.
  • If the lambda throws an unchecked exception, it rolls back.
  • status.setRollbackOnly() marks the transaction for rollback without throwing anything: tryRenew() returns false and undoes the month it had already added.

Step 8 of 9

Transactions in tests

A test annotated with @Transactional (with @SpringBootTest, @DataJpaTest, @JdbcTest…) runs inside a transaction that is rolled back when it finishes. Every test starts with the same data.

  • TestTransaction.isActive() and isFlaggedForRollback() show it.
  • To make a test commit, @Commit or @Rollback(false).
  • @JdbcTest and @DataJpaTest are transactional out of the box.

Step 9 of 9

Recap

  • PlatformTransactionManager abstracts the technology; Boot creates it and enables @Transactional.
  • @Transactional = proxy: begins, calls, commits or rolls back.
  • Default rollback: RuntimeException and Error; checked → commit.
  • Attributes: readOnly, isolation, timeout (and propagation/rollbackFor, next).
  • Programmatic: TransactionTemplate, setRollbackOnly().
  • Transactional tests: rollback at the end.

Cheatsheet →

Code

ManualTxRenewalService.java

/** Before: begin, commit and rollback written by hand around two lines of business logic. */
public class ManualTxRenewalService {
    private final PlatformTransactionManager txManager;
    private final MembershipRepository memberships;
    private final WalletRepository wallets;

    public ManualTxRenewalService(PlatformTransactionManager tx, MembershipRepository m, WalletRepository w) {
        this.txManager = tx;
        this.memberships = m;
        this.wallets = w;
    }

    public void renew(String athlete, int months, BigDecimal price) {
        TransactionStatus tx = txManager.getTransaction(new DefaultTransactionDefinition()); // BEGIN
        try {
            memberships.extend(athlete, months);
            wallets.debit(athlete, price);
            txManager.commit(tx);                                                         // COMMIT
        } catch (RuntimeException e) {
            txManager.rollback(tx);                                                       // ROLLBACK
            throw e;
        }
    }
}

RenewalServiceTest.java

@Test
void springBootWiresATransactionManagerAndAProxy() {
    assertThat(txManager).isInstanceOf(JdbcTransactionManager.class); // a DataSourceTransactionManager
    assertThat(AopUtils.isAopProxy(renewals)).isTrue();              // @Transactional ⇒ proxy
}

RenewalService.java

@Transactional // the proxy opens a transaction, calls this method, then commits or rolls back
public void renew(String athlete, int months, BigDecimal price) {
    memberships.extend(athlete, months);   // 1st write
    wallets.debit(athlete, price);         // 2nd write: may throw InsufficientFundsException
}

RenewalServiceTest.java

@Test
void aRuntimeExceptionRollsBackBothWrites() {
    assertThatThrownBy(() -> renewals.renew("Leo", 1, new BigDecimal("79.00"))) // Leo has 50
        .isInstanceOf(InsufficientFundsException.class);

    assertThat(memberships.months("Leo")).isZero();                 // the extension was undone
    assertThat(wallets.balance("Leo")).isEqualByComparingTo("50");
}

RenewalService.java

@Transactional
public void renewWithInvoice(String athlete, int months, BigDecimal price) throws InvoiceException {
    memberships.extend(athlete, months);
    wallets.debit(athlete, price);
    throw new InvoiceException("invoice printer offline"); // checked: the transaction COMMITS
}

RenewalService.java

@Transactional(readOnly = true,                    // a hint: no writes expected (drivers/ORMs may optimise)
               isolation = Isolation.REPEATABLE_READ, // what concurrent transactions may see
               timeout = 5)                        // seconds before the transaction is rolled back
public String statement(String athlete) {
    return athlete + ": " + memberships.months(athlete) + " months, " + wallets.balance(athlete) + " EUR";
}

ProgrammaticRenewalService.java

@Service
public class ProgrammaticRenewalService {
    private final TransactionTemplate tx;         // auto-configured by Spring Boot
    private final MembershipRepository memberships;
    private final WalletRepository wallets;

    public ProgrammaticRenewalService(TransactionTemplate tx, MembershipRepository m, WalletRepository w) {
        this.tx = tx;
        this.memberships = m;
        this.wallets = w;
    }

    public boolean tryRenew(String athlete, int months, BigDecimal price) {
        return tx.execute(status -> {             // BEGIN … COMMIT around the lambda
            memberships.extend(athlete, months);
            if (wallets.balance(athlete).compareTo(price) < 0) {
                status.setRollbackOnly();         // roll back WITHOUT throwing
                return false;
            }
            wallets.debit(athlete, price);
            return true;
        });
    }
}

TransactionalTestTest.java

@SpringBootTest
@Transactional // every test method runs in a transaction that is ROLLED BACK at the end
class TransactionalTestTest {
    @Autowired JdbcTemplate jdbc;

    @Test
    void changesAreRolledBackAfterTheTest() {
        jdbc.update("INSERT INTO wallet (athlete, balance) VALUES ('Zoe', 10)");

        assertThat(TestTransaction.isActive()).isTrue();
        assertThat(TestTransaction.isFlaggedForRollback()).isTrue(); // @Commit or @Rollback(false) to keep it
    }
}

RenewalService.java

@Transactional // the proxy opens a transaction, calls this method, then commits or rolls back
public void renew(String athlete, int months, BigDecimal price) {
    memberships.extend(athlete, months);   // 1st write
    wallets.debit(athlete, price);         // 2nd write: may throw InsufficientFundsException
}

Quiz

1. A @Transactional method throws an IOException (checked) after two UPDATEs. What happens to the changes?

2. What actually makes @Transactional work on a Spring bean?

3. renewTwice() isn't @Transactional and calls this.renew(), which is, twice. The second call fails. What's left in the database?

4. Which isolation level prevents dirty, non-repeatable and phantom reads?

5. A test with @SpringBootTest and @Transactional inserts a row. What happens to it when the test ends?

6. In a Spring Boot application with spring-boot-starter-jdbc, do you need @EnableTransactionManagement for @Transactional to work?

Cheatsheet → · Mock exam →

Run it