Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 38 ยท Data Access

Transactions and Database Migrations

Keep data consistent with @Transactional in Micronaut and evolve your schema safely with Flyway migrations. Runnable H2 stand-ins show commit, rollback and a migrator.

Two promises make a database trustworthy. First, a group of changes either all happen or none do: that is a transaction. Second, the structure of the database changes in a controlled, repeatable way across every environment: that is a migration. Micronaut supports both with a few annotations and one configuration block.

The Micronaut framework is not installed on this site, so its code is read-only. The runnable programs are real JDBC on the H2 database in the Java runner: one shows commit and rollback with an actual failure, the other is a miniature migration tool that applies numbered scripts exactly once.

Why transactions matter

Moving 50 dollars between two accounts is two updates: subtract from one, add to the other. If the program crashes between them, money disappears. A transaction groups both updates so the database applies them atomically. A transaction gives four guarantees, known as ACID: Atomic (all or nothing), Consistent (rules such as constraints always hold), Isolated (concurrent transactions do not see each other's half-finished work) and Durable (committed data survives a crash).

@Transactional in Micronaut

Put @Transactional (from io.micronaut.transaction.annotation or jakarta.transaction) on a service method, and Micronaut opens a transaction before it runs, commits when it returns normally, and rolls back when it throws:

Java
import io.micronaut.transaction.annotation.Transactional;

@Singleton
public class TransferService {
    private final AccountRepository accounts;

    public TransferService(AccountRepository accounts) { this.accounts = accounts; }

    @Transactional
    public void transfer(long fromId, long toId, BigDecimal amount) {
        Account from = accounts.findById(fromId).orElseThrow();
        Account to = accounts.findById(toId).orElseThrow();
        if (from.balance().compareTo(amount) < 0) {
            throw new InsufficientFundsException(fromId);
        }
        accounts.update(from.withBalance(from.balance().subtract(amount)));
        accounts.update(to.withBalance(to.balance().add(amount)));
    }
}

This is an AOP interceptor under the hood: the generated wrapper begins the transaction, calls your method, then commits or rolls back. Everything the method does through repositories joins the same transaction and the same connection.

Details worth knowing:

  • Rollback rules. By default a runtime exception rolls back. Checked exceptions do not, unless you list them with rollbackFor. Use noRollbackFor for exceptions that should still commit.
  • Read-only. @Transactional(readOnly = true) tells the driver you will not write, which can enable optimizations.
  • Propagation. If a transactional method calls another, REQUIRED (the default) joins the existing transaction. REQUIRES_NEW suspends it and starts an independent one, handy for an audit log that must be saved even if the outer work fails.
  • Isolation. @Transactional(isolation = Isolation.SERIALIZABLE) raises the isolation level. Higher levels prevent more anomalies at the cost of concurrency; the default of your database is fine for most work.
  • Keep it short. A transaction holds a pooled connection (see data sources and pools). Never call a slow remote service inside one.
  • Repositories are already transactional for their own methods. You need @Transactional yourself when one operation touches several repositories.

Micronaut Data also offers TransactionOperations for programmatic control, which is useful when you cannot use annotations:

Java
transactionOperations.executeWrite(status -> {
    // work here; call status.setRollbackOnly() to roll back
    return null;
});

Stand-in 1: commit and rollback with real JDBC

The transfer below runs on H2. The first transfer succeeds and commits. The second one fails halfway because of a database rule (a balance may not go negative), and the rollback restores the first update. A third run shows what happens without a transaction: each statement commits at once, so completed work cannot be undone when a later step fails. This is the same behavior @Transactional gives you, written out by hand.

Java Commit, rollback and autocommit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In step 3 the total stays the same only because the failing debit never ran. In a real transfer the failure could just as well happen after the debit and before the credit, and without a transaction there is no way back.

Migrations

A database schema changes over time: a new table, a new column, an index. Editing the production database by hand does not scale, and a developer's local database drifts from the team's. A migration tool keeps numbered scripts in your repository and applies the missing ones, in order, to every database. Micronaut integrates Flyway and Liquibase; Flyway is the simpler choice.

Add the module and a script folder:

GROOVY
implementation("io.micronaut.flyway:micronaut-flyway")
runtimeOnly("org.flywaydb:flyway-database-postgresql")
TEXT
src/main/resources/db/migration/
    V1__create_book.sql
    V2__add_isbn.sql
    V3__index_author.sql
YAML
flyway:
  datasources:
    default:
      enabled: true
SQL
-- V1__create_book.sql
CREATE TABLE book (
    id BIGSERIAL PRIMARY KEY,
    title VARCHAR(200) NOT NULL,
    author VARCHAR(100) NOT NULL
);

On start-up Flyway reads a table named flyway_schema_history, sees which versions are already applied, and runs only the new ones. Rules that keep teams out of trouble:

  • Never edit an applied migration. Flyway stores a checksum and refuses to start if it changed. Add a new V4__... that fixes things instead.
  • Version numbers must be unique and ordered, and the double underscore matters.
  • Make each migration small and focused, and test them against an empty database and a copy of production.
  • Add columns in steps when the app is live: first add the nullable column, deploy, backfill, then add constraints.
  • Let migrations own the schema. With Micronaut Data set schema-generate: NONE outside throwaway tests, otherwise the framework may try to create tables itself.

Transaction cheat sheet

Commit Method returns, changes are saved.
Rollback Runtime exception undoes everything.
Propagation Join the outer one or start a new one.

Keep transactions short.

1 / 2

Stand-in 2: a tiny migration runner

This program implements the core of Flyway in about forty lines: a history table, scripts sorted by version, and each script applied exactly once. Running it twice (the second run simulates an application restart) shows that nothing is applied again; adding a new script then applies only that one. It also detects a changed script by checksum, like Flyway's validation.

Java Apply each migration exactly once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

This is why the rule "never edit an applied migration" exists: the recorded checksum no longer matches, and the tool stops before you run on a database whose history you cannot trust.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A @Transactional method throws a RuntimeException halfway through. What happens to its database changes by default?

    Runtime exceptions trigger a rollback, so the changes made in that transaction disappear.
  2. 2. Which propagation setting starts a new, independent transaction even if one is already running?

    REQUIRES_NEW suspends the current transaction, which is useful for audit records that must persist.
  3. 3. Why should you add a new V4 migration instead of editing V2 after it has been applied?

    Applied migrations are history. Editing one makes environments diverge and fails Flyway's checksum check.
  4. 4. Why keep transactions short?

    A transaction keeps its connection and often database locks until it ends, so slow work inside it starves other callers.

Summary

  • A transaction makes several changes atomic; @Transactional begins, commits and rolls back for you.
  • Runtime exceptions roll back by default; configure checked exceptions with rollbackFor.
  • Use readOnly, propagation and isolation settings deliberately, and keep transactions short.
  • Migrations keep schema changes in numbered scripts tracked by a history table.
  • Flyway runs unapplied versions in order and validates checksums; never edit an applied script.
  • Let migrations own the schema in every environment except throwaway tests.

Next: Relationships and Other Data Stores