
# Transactions

`@Transactional()` on a bean method runs it in a transaction: the transaction commits when the method's `Future` completes, and rolls back when it fails. `TransactionTemplate` does the same in code. The rules are Spring's, and they are checked against Spring itself: 304 scenarios run on PostgreSQL in the starter and in a Spring Boot 4.1 application, and the CI compares their outcomes one by one.

## Why

A business operation often writes several rows that must change together: an order and its stock, a transfer between two accounts. If the second write fails, the first must be undone. A transaction gives you that, and with `@Transactional` the commit, the rollback and the joining of nested calls are not your code.

## Example

```dart
@Service()
class Checkout {
  Checkout(this.stock, this.orders, this.audit);

  final StockRepository stock;
  final OrderRepository orders;
  final AuditLog audit;

  // One transaction: the stock row stays locked until the order is saved;
  // any exception rolls everything back.
  @Transactional()
  Future<PurchaseOrder> place(int bookId) async {
    final row = (await stock.findByBookId(bookId))!;   // @Lock(pessimisticWrite)
    if (row.available == 0) {
      throw OutOfStock(bookId);                          // rolls back
    }
    row.available--;
    await stock.save(row);
    await audit.record('placed $bookId');                // joins, or not: see AuditLog
    return orders.save(PurchaseOrder(bookId: bookId));
  }
}

@Service()
class AuditLog {
  AuditLog(this.entries);

  final AuditRepository entries;

  // Its own transaction: the entry is kept even when the order rolls back.
  @Transactional(propagation: Propagation.requiresNew)
  Future<void> record(String text) => entries.save(AuditEntry(text: text));
}
```

## @Transactional

| Attribute | Default | Meaning |
|---|---|---|
| `transactionManager` | `''` | The transaction manager bean, by name or qualifier; empty for the primary one. |
| `propagation` | `Propagation.required` | How the method relates to a transaction already running. |
| `isolation` | `Isolation.defaultLevel` | The isolation level of a transaction started here. |
| `timeout` | `null` | The longest a transaction started here may run; `null` for none. |
| `readOnly` | `false` | Whether a transaction started here only reads; PostgreSQL and the in-memory store refuse writes in it. |
| `rollbackFor` | `[]` | Exception types (and subtypes) that roll back, also when a supertype is in `noRollbackFor`. |
| `noRollbackFor` | `[]` | Exception types (and subtypes) after which the transaction commits. |
| `label` | `[]` | Labels for logs and tools; not interpreted. |

On a class, it applies to each public method without its own `@Transactional`.

### Rules of use

- **It works through the bean's proxy.** A call from another bean runs in the transaction; a call through `this` inside the class does not (Spring's proxy rule).
- **The method returns a `Future`.** The transaction covers it until it completes. A synchronous method, or one returning a `Stream`, stops the start.
- **Every exception rolls back.** Dart has no checked exceptions, so the starter does not commit after any of them, as Spring does after a checked one. List the ones that should commit in `noRollbackFor`. When `rollbackFor` and `noRollbackFor` both match, the entry closest to the exception's class wins, as in Spring. The generator writes a type test and the depth in the type hierarchy for each type you list.

## Propagation

| Value | Within a transaction | Without one |
|---|---|---|
| `required` (default) | joins it | starts one |
| `supports` | joins it | runs without |
| `mandatory` | joins it | `IllegalTransactionStateException` |
| `requiresNew` | sets it aside and starts its own; does not see the outer's uncommitted rows | starts one |
| `notSupported` | sets it aside and runs in autocommit | runs without |
| `never` | `IllegalTransactionStateException` | runs without |
| `nested` | runs in a savepoint: a failure rolls back to it and the outer goes on | starts one |

A method that joins and fails marks the outer transaction rollback-only. The outer commit then throws `UnexpectedRollbackException`, even when the outer method caught the error. This is Spring's behaviour, and a common surprise.

`requiresNew` and `notSupported` take another connection from the pool: with `pool.max-size=1` (an in-memory SQLite database) they cannot run inside a transaction.

## Isolation

| Value | Means |
|---|---|
| `defaultLevel` | The store's: PostgreSQL read committed, SQLite serializable, in memory read committed. |
| `readUncommitted` | May see uncommitted changes. PostgreSQL runs it as read committed. |
| `readCommitted` | Sees only committed changes; a row read twice may differ. |
| `repeatableRead` | A row read twice is the same; new rows may appear, except in PostgreSQL (a snapshot). |
| `serializable` | As if one after the other; a conflict fails one (`CannotSerializeTransactionException`). |

A store offers some levels: PostgreSQL all of them, SQLite `defaultLevel` and `serializable`, the in-memory store read committed only. Asking for a level the store does not offer fails when the transaction starts (`InvalidIsolationLevelException`), never silently with a weaker one.

What PostgreSQL's levels show, measured by the comparison with Spring:

| | read committed | repeatable read | serializable |
|---|---|---|---|
| dirty read | no | no | no |
| non-repeatable read | yes | no | no |
| phantom | yes | no | no |
| lost update, read-modify-write | the second overwrites | the second fails (`40001`) | the second fails |
| lost update, `balance = balance + n` | none: the second waits, then adds | the second fails (`40001`) | the second fails |
| write skew | yes | yes | the second commit fails (`40001`) |

## Timeouts and read-only

- A transaction that runs past its `timeout` is marked rollback-only and its statement cancelled; its commit throws `UnexpectedRollbackException`. On PostgreSQL the statement is cancelled on the server (`QueryTimeoutException`) and the connection stays usable.
- `spring.jdbc.template.query-timeout` bounds each statement of the `JdbcTemplate` beans, inside or outside a transaction.
- `timeout`, `isolation` and `readOnly` apply only to a transaction that starts at that method; a method that joins keeps the outer's settings.

## TransactionTemplate

```dart
@Service()
class Restock {
  Restock(this.transactions, this.stock);

  final TransactionTemplate transactions;   // a bean over the only transaction manager
  final StockRepository stock;

  Future<void> add(int bookId, int count) => transactions.executeWithoutResult((status) async {
    final row = (await stock.findByBookId(bookId))!;
    if (count <= 0) {
      status.setRollbackOnly();             // roll back without throwing
      return;
    }
    row.available += count;
    await stock.save(row);
  });
}
```

- `execute(action)` returns the action's result once the transaction has committed; `executeWithoutResult(action)` returns nothing.
- `TransactionTemplate(manager, [definition])` makes one with other settings: `TransactionDefinition(propagation:, isolation:, timeout:, readOnly:, name:)`.
- The `transactionTemplate` bean exists when there is a single transaction manager.

## Several transaction managers

Each data source has its own manager: `transactionManager` for the primary one, `<name>TransactionManager` (qualified `<name>`) for each `spring.datasources.<name>`. Choose one by name:

```dart
@Transactional(transactionManager: 'stats')
Future<void> visit(String page) => visits.save(Visit(page: page));
```

A transaction covers one manager. Work on two databases in one method is two transactions, each committed on its own.

## The transaction follows await

Spring keeps the current transaction in a thread-local. Dart has one thread and many interleaved tasks, so the transaction lives in a `Zone`: it follows every `await` of the method, and two requests running at the same time never share one.

Work started inside the transaction without `await`, and still running after it ended, fails with `IllegalTransactionStateException` when it uses the database, instead of running outside the transaction:

```dart
@Transactional()
Future<void> wrong() async {
  unawaited(books.save(Book(title: 'Late')));   // fails if it outlives the transaction
}
```

## Repositories and transactions

The write methods of a repository (`save`, `saveAll`, `delete*`, `deleteBy`) run in a `required` transaction of its store, as Spring's `SimpleJdbcRepository` is `@Transactional`: `saveAll` and an aggregate with its children are atomic, and inside your transaction they join it. The read methods join a running transaction, or run on their own.

## In Spring (Java)

```java
@Transactional(propagation = Propagation.REQUIRES_NEW, noRollbackFor = NotifyFailed.class)
public void record(String text) { ... }
```

The differences:

- `transactionManager: 'x'` instead of the positional `value`: Dart cannot mix an optional positional parameter with named ones.
- Every exception rolls back by default.
- A `@Lock` query outside a transaction fails instead of running in autocommit.
- The transaction is bound to a `Zone`, not a thread.

## See also

- [Locks](locks.md)
- [Data sources](data-sources.md)
- [Errors](errors.md)
