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
. Scripts are never edited after they have run; a new change is a new script.V2__add_email.sql - A history table:
, 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.flyway_schema_history
Spring Boot runs Flyway's migrateDataSource
| Name | Type | Runs | Best for |
|---|---|---|---|
V1__create_customer.sql | Versioned | Once, in version order | Tables, columns, data fixes: almost every change |
R__customer_view.sql | Repeatable | After the versioned ones, again whenever its checksum changes | Views, functions, stored procedures, kept as one current definition |
V3__Split_names | Java migration | Once, like a versioned script | Changes that need code: computed values, conversions, calls to libraries |
U2__add_email.sql | Undo | Only on flyway undo | Paid Flyway editions only |
The version is the part between VV1.2.1__spring-boot-starter-flywayorg.flywaydb:flyway-coreflyway-database-postgresql
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/migrationspring.flyway.locations
CREATE TABLE customer (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
INSERT INTO customer VALUES (1, 'Ann'), (2, 'Bob');
ALTER TABLE customer ADD COLUMN email VARCHAR(100);
UPDATE customer SET email = LOWER(name) || '@example.com';
CREATE OR REPLACE VIEW customer_summary AS
SELECT id, name || ' <' || email || '>' AS label FROM customer;
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);
}
}
}
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
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:
ALTER TABLE customer ADD COLUMN status VARCHAR(10) DEFAULT 'ACTIVE' NOT NULL;
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(""));
}
}
}
}
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.
lists every migration with its state. With V4 on the classpath but migration switched off byFlyway.info() , V4 isspring.flyway.enabled=false . This is the check to run before a deployment.Pending , which drops every object in the schema, refused to run:clean() iscleanDisabled by default since Flyway 9. Settrue only for databases you are prepared to lose.spring.flyway.clean-disabled=false
Spring Boot creates the Flywayspring.flyway.enabledtrueFlyway.configure()
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>
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));
}
}
}
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
and its class name as the script. Java migrations have no checksum by default, so Flyway cannot detect changes to them; overrideJDBC if you want that.getChecksum() - The migration filled the new
column from each name, A and B, using the JDBCinitial from theConnection , inside the migration's transaction.Context
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:
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");
}
}
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
column. The next start failed withname : 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,FlywayValidateException updates the stored checksum.flyway repair - 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
it ran V2 after V3, and the history shows the order 1, 3, 2.spring.flyway.out-of-order=true - Case 3: the database already had a
table but no history table. Flyway refused to touch a non-empty schema it does not know.customer withbaseline-on-migrate=true recorded version 1 as a baseline, meaning "the schema is already at version 1", and ran only V2.baseline-version=1
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
Configuration that matters
| Property | Default | Use |
|---|---|---|
spring.flyway.locations | classpath:db/migration | Where scripts and Java migrations are found; filesystem: |
spring.flyway.enabled | true | Turn off migration at startup, for example when a pipeline runs it instead |
spring.flyway.baseline-on-migratebaseline-version | false | Adopting Flyway on an existing database |
spring.flyway.out-of-order | false | Allow late lower versions to run |
spring.flyway.clean-disabled | true | Keep clean() |
spring.flyway.urluserpassword | The application's DataSource | Migrate with an account that may change the schema, while the application uses one that may not |
spring.flyway.placeholders.* | None | Values substituted for ${name} |
With JPA, set spring.jpa.hibernate.ddl-auto=validate
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
of millions of rows in a migration holds locks during startup. Large backfills belong in a batch job.UPDATE - 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
| Change | Use |
|---|---|
| Tables, columns, indexes, constraints | A versioned SQL migration |
| Views, functions, procedures | A repeatable R__ |
| Data conversion that needs code | A Java migration with plain JDBC |
| Logging, notifications or checks around migrations | A Callback |
| An existing database without history | baseline-on-migrate |
| Parallel branches adding migrations | Timestamp versions, or out-of-order |
| Rollback scripts and multi-database changelogs |
Flyway's model is deliberately simple: plain SQL files, applied once, in order. For a comparison with Liquibase's changelog model, see the