Flyway database migrations with Spring Boot

Flyway keeps a database schema in step with the code by running numbered SQL scripts in order and recording each one in a history table. Spring Boot runs it at startup, before anything else touches the database. This page runs the whole lifecycle against H2: first migrations, new releases, Java migrations and callbacks, and the three validation errors every team meets.

Contents

How Flyway works

A database schema changes with the code: a new column, a new table, an index. Those changes have to reach every developer's database, the test database and production, in the same order and exactly once each. Flyway does this with two ideas:

  • Migrations: each change is a script with a version in its name, such as V2__add_email.sql. Scripts are never edited after they have run; a new change is a new script.
  • A history table: flyway_schema_history, in the database itself, records every migration that has run, with its checksum. At startup, Flyway compares the scripts it finds with the history, runs the ones that are missing, in version order, and refuses to start if an applied script has changed.

Spring Boot runs Flyway's migrate while the application starts, after the DataSource is created and before JPA, so that Hibernate always sees the current schema. Script names follow a fixed pattern:

Flyway migration types
NameTypeRunsBest for
V1__create_customer.sqlVersionedOnce, in version orderTables, columns, data fixes: almost every change
R__customer_view.sqlRepeatableAfter the versioned ones, again whenever its checksum changesViews, functions, stored procedures, kept as one current definition
V3__Split_names (a Java class)Java migrationOnce, like a versioned scriptChanges that need code: computed values, conversions, calls to libraries
U2__add_email.sqlUndoOnly on flyway undoPaid Flyway editions only

The version is the part between V and the two underscores; it can have dots, such as V1.2.1__, and is compared as numbers, so 1.10 comes after 1.9. The rest becomes the description. In Spring Boot 4, add spring-boot-starter-flyway; in Spring Boot 3 you added org.flywaydb:flyway-core directly. Since Flyway 10, many databases also need a database module, such as flyway-database-postgresql; H2 support is in the core jar. The examples use Spring Boot 4.1, which brings Flyway 12.4, against H2.

The first migrations

Two versioned scripts create a table and then add a column, and a repeatable script defines a view over it. Spring Boot looks in classpath:db/migration by default; this program sets spring.flyway.locations to its own folder:

SQL
CREATE TABLE customer (
    id   INT PRIMARY KEY,
    name VARCHAR(50) NOT NULL
);
INSERT INTO customer VALUES (1, 'Ann'), (2, 'Bob');
SQL
ALTER TABLE customer ADD COLUMN email VARCHAR(100);
UPDATE customer SET email = LOWER(name) || '@example.com';
SQL
CREATE OR REPLACE VIEW customer_summary AS
SELECT id, name || ' <' || email || '>' AS label FROM customer;
Java
package flyway.first;

import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;

@SpringBootApplication
public class FirstMigrations {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(FirstMigrations.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "logging.level.org.flywaydb.core.internal.command.DbMigrate", "INFO",
                "logging.level.org.flywaydb.core.internal.database.base.Database", "ERROR",
                "logging.pattern.console", "%logger{0}: "
                        + "%replace(%msg){' \\(execution time [^)]+\\)', ''}%n",
                "spring.flyway.locations", "classpath:flyway/basic"));
        try (var context = app.run(args)) {
            JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
            System.out.println("-- flyway_schema_history");
            jdbc.query("SELECT \"installed_rank\", \"version\", \"description\", \"type\","
                    + " \"script\", \"success\" FROM \"flyway_schema_history\" ORDER BY 1",
                    (rs, row) -> String.format("%d | %-4s | %-15s | %-3s | %-25s | %s",
                            rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4),
                            rs.getString(5), rs.getBoolean(6)))
                    .forEach(System.out::println);
            System.out.println("-- customer_summary view");
            jdbc.queryForList("SELECT label FROM customer_summary ORDER BY id", String.class)
                    .forEach(System.out::println);
        }
    }
}
Output
DbMigrate: Current version of schema "PUBLIC": << Empty Schema >>
DbMigrate: Migrating schema "PUBLIC" to version "1 - create customer"
DbMigrate: Migrating schema "PUBLIC" to version "2 - add email"
DbMigrate: Migrating schema "PUBLIC" with repeatable migration "customer view"
DbMigrate: Successfully applied 3 migrations to schema "PUBLIC", now at version v2
-- flyway_schema_history
-1 | null | << Flyway Schema History table created >> | TABLE |                           | true
1 | 1    | create customer | SQL | V1__create_customer.sql   | true
2 | 2    | add email       | SQL | V2__add_email.sql         | true
3 | null | customer view   | SQL | R__customer_view.sql      | true
-- customer_summary view
Ann <ann@example.com>
Bob <bob@example.com>
  • The database was empty, so Flyway ran V1, then V2, then the repeatable script, and reported version 2. Repeatable migrations always run after the versioned ones.
  • The history table has one row per migration: rank, version, description, type and script name. The repeatable migration has no version. The row with rank -1 is a marker Flyway wrote when it created the history table.
  • The view shows the email column that V2 added and filled, so all three scripts ran against the same, current schema.

The program's logging setup shows Flyway's DbMigrate messages, with the execution times removed so that the output does not change between runs. It also hides one warning: Flyway 12.4 logs that H2 2.4.240 is newer than the latest H2 version it was verified with, 2.3.232. The migrations still ran correctly.

Releases: what runs on the next start

The real value of Flyway shows on the second and later starts. This program starts the application four times against one in-memory database that outlives each context, as a production database outlives each deployment:

SQL
ALTER TABLE customer ADD COLUMN status VARCHAR(10) DEFAULT 'ACTIVE' NOT NULL;
Java
package flyway.evolve;

import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.MigrationInfo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class Evolving {

    static ConfigurableApplicationContext start(String... extra) {
        SpringApplication app = new SpringApplication(Evolving.class);
        Map<String, Object> props = new HashMap<>(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "logging.level.org.flywaydb.core.internal.command.DbMigrate", "INFO",
                "logging.level.org.flywaydb.core.internal.database.base.Database", "ERROR",
                "logging.pattern.console", "  %logger{0}: "
                        + "%replace(%msg){' \\(execution time [^)]+\\)', ''}%n",
                "spring.datasource.url", "jdbc:h2:mem:evolve;DB_CLOSE_DELAY=-1"));
        for (int i = 0; i < extra.length; i += 2) {
            props.put(extra[i], extra[i + 1]);
        }
        app.setDefaultProperties(props);
        return app.run();
    }

    static void info(Flyway flyway) {
        for (MigrationInfo m : flyway.info().all()) {
            System.out.printf("  %-4s %-15s %s%n", m.getVersion() == null ? "R" : m.getVersion(),
                    m.getDescription(), m.getState().getDisplayName());
        }
    }

    public static void main(String[] args) {
        System.out.println("Release 1: V1, V2 and R");
        start("spring.flyway.locations", "classpath:flyway/basic").close();

        System.out.println("Restart with the same scripts");
        start("spring.flyway.locations", "classpath:flyway/basic").close();

        System.out.println("Release 2 adds V3");
        try (var context = start("spring.flyway.locations",
                "classpath:flyway/basic,classpath:flyway/extra")) {
            info(context.getBean(Flyway.class));
        }

        System.out.println("V4 on the classpath, spring.flyway.enabled=false");
        try (var context = start("spring.flyway.enabled", "false")) {
            Flyway flyway = Flyway.configure()
                    .dataSource(context.getBean(DataSource.class))
                    .locations("classpath:flyway/basic", "classpath:flyway/extra",
                            "classpath:flyway/later")
                    .load();
            info(flyway);
            try {
                flyway.clean();
            } catch (FlywayException e) {
                System.out.println("  clean(): " + e.getMessage().lines().findFirst().orElse(""));
            }
        }
    }
}
Output
Release 1: V1, V2 and R
  DbMigrate: Current version of schema "PUBLIC": << Empty Schema >>
  DbMigrate: Migrating schema "PUBLIC" to version "1 - create customer"
  DbMigrate: Migrating schema "PUBLIC" to version "2 - add email"
  DbMigrate: Migrating schema "PUBLIC" with repeatable migration "customer view"
  DbMigrate: Successfully applied 3 migrations to schema "PUBLIC", now at version v2
Restart with the same scripts
  DbMigrate: Current version of schema "PUBLIC": 2
  DbMigrate: Schema "PUBLIC" is up to date. No migration necessary.
Release 2 adds V3
  DbMigrate: Current version of schema "PUBLIC": 2
  DbMigrate: Migrating schema "PUBLIC" to version "3 - add status"
  DbMigrate: Successfully applied 1 migration to schema "PUBLIC", now at version v3
  1    create customer Success
  2    add email       Success
  R    customer view   Success
  3    add status      Success
V4 on the classpath, spring.flyway.enabled=false
  1    create customer Success
  2    add email       Success
  R    customer view   Success
  3    add status      Success
  4    index email     Pending
  clean(): Unable to execute clean as it has been disabled with the 'flyway.cleanDisabled' property.
  • The first start applied all three scripts. The restart with the same scripts found nothing to do: "Schema is up to date. No migration necessary."
  • Release 2 added V3, and only V3 ran. The repeatable view script did not run again, because its checksum had not changed.
  • Flyway.info() lists every migration with its state. With V4 on the classpath but migration switched off by spring.flyway.enabled=false, V4 is Pending. This is the check to run before a deployment.
  • clean(), which drops every object in the schema, refused to run: cleanDisabled is true by default since Flyway 9. Set spring.flyway.clean-disabled=false only for databases you are prepared to lose.

Spring Boot creates the Flyway bean only while spring.flyway.enabled is true, which is why the last step builds its own with Flyway.configure(). The same API runs migrations from tests, command-line tools or a separate deployment step.

Java migrations and callbacks

Some changes are easier in Java than in SQL: computing values, converting formats, or calling a library. A Java migration is a class whose name follows the same V<version>__<description> pattern. Callbacks run code at points in the migration, such as before each migration. Spring Boot registers beans of both kinds with Flyway automatically:

Java
package flyway.java;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Map;
import org.flywaydb.core.api.callback.Callback;
import org.flywaydb.core.api.callback.Context;
import org.flywaydb.core.api.callback.Event;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class JavaMigrationAndCallback {

    @Component
    static class V3__Split_names extends BaseJavaMigration {
        // Flyway has two Context types; the imported one is for callbacks
        @Override
        public void migrate(org.flywaydb.core.api.migration.Context context) throws Exception {
            var connection = context.getConnection();
            try (Statement ddl = connection.createStatement()) {
                ddl.execute("ALTER TABLE customer ADD COLUMN initial CHAR(1)");
            }
            try (Statement select = connection.createStatement();
                    ResultSet rows = select.executeQuery("SELECT id, name FROM customer");
                    PreparedStatement update = connection.prepareStatement(
                            "UPDATE customer SET initial = ? WHERE id = ?")) {
                while (rows.next()) {
                    update.setString(1, rows.getString("name").substring(0, 1));
                    update.setInt(2, rows.getInt("id"));
                    update.addBatch();
                }
                update.executeBatch();
            }
        }
    }

    @Component
    static class Announcer implements Callback {
        @Override
        public boolean supports(Event event, Context context) {
            return event == Event.BEFORE_EACH_MIGRATE || event == Event.AFTER_MIGRATE;
        }

        @Override
        public boolean canHandleInTransaction(Event event, Context context) {
            return true;
        }

        @Override
        public void handle(Event event, Context context) {
            if (event == Event.BEFORE_EACH_MIGRATE) {
                System.out.println("callback: about to run " + context.getMigrationInfo()
                        .getScript());
            } else {
                System.out.println("callback: migration finished");
            }
        }

        @Override
        public String getCallbackName() {
            return "announcer";
        }
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(JavaMigrationAndCallback.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "logging.level.org.flywaydb.core.internal.database.base.Database", "ERROR",
                "spring.flyway.locations", "classpath:flyway/basic"));
        try (var context = app.run(args)) {
            JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
            jdbc.query("SELECT \"version\", \"type\", \"script\" FROM \"flyway_schema_history\""
                    + " WHERE \"installed_rank\" > 0 ORDER BY \"installed_rank\"",
                    (rs, row) -> rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3))
                    .forEach(System.out::println);
            System.out.println(jdbc.queryForList(
                    "SELECT name || '=' || initial FROM customer ORDER BY id", String.class));
        }
    }
}
Output
callback: about to run V1__create_customer.sql
callback: about to run V2__add_email.sql
callback: about to run flyway.java.JavaMigrationAndCallback$V3__Split_names
callback: about to run R__customer_view.sql
callback: migration finished
1 SQL V1__create_customer.sql
2 SQL V2__add_email.sql
3 JDBC flyway.java.JavaMigrationAndCallback$V3__Split_names
null SQL R__customer_view.sql
[Ann=A, Bob=B]
  • The callback ran before each of the four migrations and once at the end. The Java migration ran third, between V2 and the repeatable script, because its class name gives it version 3.
  • Its history row has type JDBC and its class name as the script. Java migrations have no checksum by default, so Flyway cannot detect changes to them; override getChecksum() if you want that.
  • The migration filled the new initial column from each name, A and B, using the JDBC Connection from the Context, inside the migration's transaction.

Keep Java migrations independent of the application's entities and repositories. The entities describe the latest schema, not the schema at version 3, and a migration that uses them breaks as soon as a later version changes the entity. Plain JDBC, as here, keeps working for as long as the migration exists.

Validation errors: checksums, gaps and existing databases

Before migrating, Flyway validates the history against the scripts it finds. Three situations fail validation in every team sooner or later. This program creates each one, with an edited V1, a V2 that appears after V3, and a database that existed before Flyway:

Java
package flyway.traps;

import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

@SpringBootApplication
public class ValidationTraps {

    static void start(String db, String... extra) {
        SpringApplication app = new SpringApplication(ValidationTraps.class);
        Map<String, Object> props = new HashMap<>(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "OFF",
                "spring.datasource.url", "jdbc:h2:mem:" + db + ";DB_CLOSE_DELAY=-1"));
        for (int i = 0; i < extra.length; i += 2) {
            props.put(extra[i], extra[i + 1]);
        }
        app.setDefaultProperties(props);
        try (var context = app.run()) {
            System.out.println("  started, versions applied in this order: " + context
                    .getBean(JdbcTemplate.class).queryForList("SELECT \"version\" FROM"
                            + " \"flyway_schema_history\" WHERE \"version\" IS NOT NULL"
                            + " ORDER BY \"installed_rank\"", String.class));
        } catch (RuntimeException e) {
            Throwable cause = e;
            while (cause.getCause() != null) {
                cause = cause.getCause();
            }
            System.out.println("  startup failed: " + cause.getClass().getSimpleName());
            cause.getMessage().lines()
                    .filter(l -> !l.isBlank() && !l.contains("http")).limit(4)
                    .forEach(l -> System.out.println("    " + l.strip()));
        }
    }

    public static void main(String[] args) {
        System.out.println("1. V1 edited after it was applied");
        start("edit", "spring.flyway.locations", "classpath:flyway/basic");
        start("edit", "spring.flyway.locations", "classpath:flyway/edited");

        System.out.println("2. V2 arrives after V3 was applied");
        start("gap", "spring.flyway.locations", "classpath:flyway/gap");
        start("gap", "spring.flyway.locations", "classpath:flyway/gap,classpath:flyway/legacy");
        start("gap", "spring.flyway.locations", "classpath:flyway/gap,classpath:flyway/legacy",
                "spring.flyway.out-of-order", "true");

        System.out.println("3. An existing database without a history table");
        new JdbcTemplate(new DriverManagerDataSource("jdbc:h2:mem:legacy;DB_CLOSE_DELAY=-1",
                "sa", ""))
                .execute("CREATE TABLE customer (id INT PRIMARY KEY, name VARCHAR(50))");
        start("legacy", "spring.flyway.locations", "classpath:flyway/legacy");
        start("legacy", "spring.flyway.locations", "classpath:flyway/legacy",
                "spring.flyway.baseline-on-migrate", "true",
                "spring.flyway.baseline-version", "1");
    }
}
Output
1. V1 edited after it was applied
  started, versions applied in this order: [1, 2]
  startup failed: FlywayValidateException
    Validate failed: Migrations have failed validation
    Migration checksum mismatch for migration version 1
    -> Applied to database : -1844195464
    -> Resolved locally    : -1598595469
2. V2 arrives after V3 was applied
  started, versions applied in this order: [1, 3]
  startup failed: FlywayValidateException
    Validate failed: Migrations have failed validation
    Detected resolved migration not applied to database: 2.
    To ignore this migration, set -ignoreMigrationPatterns='*:ignored'. To allow executing this migration, set -outOfOrder=true.
  started, versions applied in this order: [1, 3, 2]
3. An existing database without a history table
  startup failed: FlywayException
    Found non-empty schema(s) "PUBLIC" but no schema history table. Use baseline() or set baselineOnMigrate to true to initialize the schema history table.
  started, versions applied in this order: [1, 2]
  • Case 1: V1 was applied, then edited to widen the name column. The next start failed with FlywayValidateException: the checksum in the history (-1844195464) does not match the file (-1598595469). Editing an applied script never changes the databases that already ran it, so Flyway stops rather than let them drift apart. Write the change as a new migration instead. If the edit was harmless, such as a comment, flyway repair updates the stored checksum.
  • Case 2: V1 and V3 were applied, then V2 appeared, as happens when two branches are merged. By default Flyway refuses: "Detected resolved migration not applied to database: 2". With spring.flyway.out-of-order=true it ran V2 after V3, and the history shows the order 1, 3, 2.
  • Case 3: the database already had a customer table but no history table. Flyway refused to touch a non-empty schema it does not know. baseline-on-migrate=true with baseline-version=1 recorded version 1 as a baseline, meaning "the schema is already at version 1", and ran only V2.

Out-of-order migrations are safe only when the late script does not depend on the ones that ran before it. Many teams avoid the problem by using timestamps as versions, such as V20261114_1030__add_email.sql, which makes collisions between branches rare.

Configuration that matters

Common spring.flyway properties
PropertyDefaultUse
spring.flyway.locationsclasspath:db/migrationWhere scripts and Java migrations are found; filesystem: paths work too
spring.flyway.enabledtrueTurn off migration at startup, for example when a pipeline runs it instead
spring.flyway.baseline-on-migrate, baseline-versionfalse, 1Adopting Flyway on an existing database
spring.flyway.out-of-orderfalseAllow late lower versions to run
spring.flyway.clean-disabledtrueKeep clean() from dropping the schema
spring.flyway.url, user, passwordThe application's DataSourceMigrate with an account that may change the schema, while the application uses one that may not
spring.flyway.placeholders.*NoneValues substituted for ${name} in scripts

With JPA, set spring.jpa.hibernate.ddl-auto=validate: Flyway creates the schema, and Hibernate only checks at startup that the entities match it. When several instances start at the same time, Flyway takes a database lock so that only one of them migrates; the others wait and then find nothing to do.

Writing migrations that are safe to deploy

  • Never edit an applied migration: add a new one. The checksum error in case 1 is Flyway enforcing this.
  • Make changes backward compatible: during a rolling deployment, old instances run against the new schema. Add a column as nullable or with a default, deploy the code that uses it, and drop old columns in a later release.
  • Keep data changes small: an UPDATE of millions of rows in a migration holds locks during startup. Large backfills belong in a batch job.
  • Watch transactional DDL: PostgreSQL runs each migration in a transaction, so a failed script leaves no trace. MySQL commits each DDL statement immediately, so a script that fails halfway leaves a partly changed schema and a failed history row to repair by hand. One change per script limits the damage.
  • Test against the real database: H2 accepts SQL that PostgreSQL or MySQL reject, and the other way round. Run migrations against the production database type in CI, for example with Testcontainers.

Choosing a migration style

Which Flyway feature fits which change
ChangeUse
Tables, columns, indexes, constraintsA versioned SQL migration
Views, functions, proceduresA repeatable R__ migration holding the current definition
Data conversion that needs codeA Java migration with plain JDBC
Logging, notifications or checks around migrationsA Callback bean
An existing database without historybaseline-on-migrate with the version that matches its schema
Parallel branches adding migrationsTimestamp versions, or out-of-order for independent scripts
Rollback scripts and multi-database changelogsLiquibase

Flyway's model is deliberately simple: plain SQL files, applied once, in order. For a comparison with Liquibase's changelog model, see the Liquibase page. The H2 page explains the in-memory databases used here, and multiple data sources covers migrating a second database.