Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 36 ยท Data with Panache

Transactions and Flyway Migrations

Use @Transactional in Quarkus, learn when a transaction rolls back, and manage the database schema with Flyway migrations instead of drop-and-create.

Two things keep a database trustworthy: transactions, which make a group of changes succeed or fail as one unit, and migrations, which change the schema in a controlled, repeatable way. Quarkus supports both with very little code. This lesson covers @Transactional, its rollback rules, and the Flyway extension.

The real Quarkus, Narayana and Flyway code is read-only. The stand-ins model a transaction with rollback, and the way Flyway decides which migrations to run.

Transactions with @Transactional

A transaction is all-or-nothing: either every change inside it is saved (commit) or none is (rollback). The classic example is a transfer between two accounts, where taking money from one without adding it to the other would be a disaster.

In Quarkus you put @Transactional on a CDI bean method or class (and on a resource method):

Java
import jakarta.transaction.Transactional;

@ApplicationScoped
public class TransferService {

    @Transactional
    public void transfer(long fromId, long toId, long cents) {
        Account from = Account.findById(fromId);
        Account to = Account.findById(toId);
        from.balance -= cents;
        if (from.balance < 0) {
            throw new InsufficientFunds(fromId);
        }
        to.balance += cents;
    }
}

Quarkus starts a transaction before the method, and commits when it returns normally. If the method throws, the transaction is rolled back, and nothing is written. Because this is done by an interceptor, it follows the interceptor rules: the call must go through the container, so a call from another method of the same class (this.transfer(...)) does not start a transaction.

Use jakarta.transaction.Transactional in Quarkus (the Jakarta annotation). Reads such as findById work without a transaction, but changes need one, otherwise you get TransactionRequiredException.

Rollback rules

By default, a transaction rolls back for unchecked exceptions (RuntimeException and Error) and commits for checked exceptions. You can change that:

Java
@Transactional(rollbackOn = IOException.class)           // checked exception also rolls back
@Transactional(dontRollbackOn = ValidationFailed.class)  // runtime exception still commits

This default surprises many people: a method that throws Exception (checked) commits whatever it did before the throw.

Propagation

@Transactional(Transactional.TxType.X) decides what happens when a transaction already exists:

Type Behaviour
REQUIRED (default) join the existing transaction or start one
REQUIRES_NEW suspend the current one and start a new one (useful for audit logs that must be saved even if the outer transaction fails)
MANDATORY must already be in a transaction, otherwise error
SUPPORTS join if present, otherwise run without
NOT_SUPPORTED suspend the current transaction
NEVER error if a transaction exists

Quarkus also has a programmatic API: QuarkusTransaction.requiringNew().run(() -> ...), handy when you need a transaction around a block rather than a whole method. Keep transactions short: do not call slow remote services or wait for user input inside one, because open transactions hold locks and database connections.

Java Stand-in: all-or-nothing with rollback

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.

The last run shows the default rule that surprises people: the debit stayed because the exception was checked.

Managing the schema

In dev and test you can let Hibernate create tables from your entities. It is fast, but in production it is dangerous: it cannot move data, rename columns safely, or give you a history of changes. The solution is schema migrations: numbered SQL scripts, applied in order, recorded in a table so each runs exactly once. Quarkus integrates Flyway (and also Liquibase).

Add the extension and a driver:

XML
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-flyway</artifactId>
</dependency>

Put scripts in src/main/resources/db/migration. The file name carries the version:

TEXT
V1__create_book_tables.sql
V1_1__add_isbn.sql
V2__create_review_table.sql
R__refresh_views.sql
SQL
-- V1__create_book_tables.sql
CREATE TABLE author (
    id   BIGINT PRIMARY KEY,
    name VARCHAR(120) NOT NULL
);

CREATE TABLE book (
    id        BIGINT PRIMARY KEY,
    title     VARCHAR(120) NOT NULL,
    year      INT NOT NULL,
    author_id BIGINT NOT NULL REFERENCES author (id)
);

Configuration:

PROPERTIES
quarkus.flyway.migrate-at-start=true
quarkus.flyway.baseline-on-migrate=true
%prod.quarkus.hibernate-orm.database.generation=none
%dev.quarkus.hibernate-orm.database.generation=none

With migrate-at-start, Flyway runs pending scripts when the application starts. It records each run in the table flyway_schema_history, along with a checksum of the script. If you edit a script that has already been applied, Flyway refuses to start: applied migrations are history and must never change. To fix something, add a new version.

Rules of thumb:

  • Version scripts (V...) run once, in version order. Repeatable scripts (R__...) re-run when their content changes.
  • Once a script is in a shared branch, treat it as immutable.
  • Make migrations backward compatible across a deploy (add a column first, use it, remove the old one later), so old and new app versions can run side by side during a rolling update.
  • Use import.sql or a test-only migration (%test location) for sample data, never in production migrations.
Java Stand-in: which migrations run?

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.

Keep data safe

Transaction Many changes, one outcome.
Rollback Runtime exceptions undo the work.
Short Hold locks for as little time as possible.

Checked exceptions commit unless you say otherwise.

1 / 2

Putting it together

A typical production setup: Flyway owns the schema, Hibernate only validates or does nothing (database.generation=none or validate), services use @Transactional around each use case, and tests run against a Dev Services database that is migrated by the same scripts, so tests exercise the real schema. In the Bookshop API project you will see this stack end to end.

Do not put @Transactional on every method by reflex. A transaction around a long-running method holds a database connection and its locks. Put it on the smallest method that must be atomic.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. By default, which exceptions cause a @Transactional method to roll back?

    Unchecked exceptions roll back; checked exceptions commit unless you configure rollbackOn.
  2. 2. Why does this.transfer(...) inside the same class not start a transaction?

    @Transactional is implemented by an interceptor. Calls that do not go through the container are not intercepted.
  3. 3. What does Flyway do when an already applied migration file is edited?

    Flyway stores a checksum for each applied script and fails validation if it changes.
  4. 4. Which setting is a good fit for production when Flyway manages the schema?

    Drop-and-create would erase production data. With Flyway owning the schema, Hibernate should not change it.
  5. 5. When is REQUIRES_NEW useful?

    It suspends the current transaction and commits independently.

Summary

  • @Transactional makes a method atomic; unchecked exceptions roll back, checked ones commit unless configured.
  • Propagation types such as REQUIRED and REQUIRES_NEW control how transactions nest. Keep transactions short.
  • Flyway applies versioned SQL scripts from db/migration once each and verifies checksums.
  • In production let Flyway own the schema and set Hibernate's schema generation to none.

Next: Configuration Properties and Profiles