Skip to content
Tutorials Center
My learning

Topics

Lesson 97 of 119 ยท Architecture and Deployment

Database Migrations with Flyway

Manage database schema changes with Flyway in Spring Boot, from versioned and repeatable migrations and checksums to baselines for existing databases, repair and safe team workflows.

Your code lives in Git and every release is a numbered build, but what about the database? Imagine a developer adds a year column to the book table on their laptop, the code starts using it, and the feature ships. Production does not have that column, because nobody remembered to run the ALTER TABLE. Or someone ran it by hand on the staging server but forgot the test server. Over time every environment has a slightly different schema, and nobody can say which one is right.

Database migration tools fix this by treating schema changes like code. Every change is a small, numbered SQL script stored in the repository. The tool remembers which scripts each database has already run, and applies the missing ones, in order, exactly once. Flyway is the most widely used tool in the Java world, and Spring Boot runs it automatically at application startup. This lesson builds a miniature Flyway on H2 so you can see what it does behind the scenes, then covers the real configuration, the baseline feature for existing databases and the rules that keep teams out of trouble. It extends the short Flyway section in Deploying Java Applications and uses ideas from JDBC.

The idea: a history table and numbered scripts

Flyway looks for scripts in src/main/resources/db/migration (on the classpath). The file name carries all the information it needs:

Text
V1__create_book.sql          versioned migration, version 1
V1.1__add_index.sql          version 1.1
V2__add_published_year.sql             version 2
V10__add_isbn.sql            version 10
R__book_titles_view.sql      repeatable migration
  • Versioned migrations (V<version>__<description>.sql) run exactly once, in version order. After a migration succeeds, Flyway records it in a history table (named flyway_schema_history by default) with its version, description, checksum, who ran it and when.
  • Repeatable migrations (R__<description>.sql) have no version. Flyway re-runs them whenever their content (checksum) changes, after all versioned migrations. They suit objects you fully redefine each time: views, stored procedures, reference data refreshes.
  • The separator is two underscores. Versions are compared numerically, part by part, so V10 comes after V2.
flowchart TD
  S["Application starts"] --> H{"History table exists?"}
  H -->|"no, empty database"| C["Create history table"]
  H -->|"no, tables already exist"| E["Fail unless baselineOnMigrate is set"]
  H -->|"yes"| V["Validate: checksums of applied scripts unchanged?"]
  C --> V
  V -->|"mismatch"| F["Fail startup with a clear error"]
  V -->|"ok"| P["Find pending versioned scripts"]
  P --> A["Apply each in version order and record it"]
  A --> R["Re-run repeatable scripts whose checksum changed"]
  R --> D["Application continues starting"]

Validation happens before anything is applied, so a modified old script stops the deployment instead of silently diverging.

The most important rule follows from this design: never edit a migration that has already run anywhere. Its checksum is stored, and a changed file makes validation fail. To change something, add a new migration.

First, a look at the naming rules, since they cause the most beginner mistakes. The example parses file names the way Flyway does and sorts the versions numerically:

Java Migration file names and version order

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.

Plain text sorting would put V10 before V2, which is why Flyway compares numbers. Look at the three ignored names: a single underscore, a lowercase v and a wrong extension are all skipped without an error by default, so a misspelled migration is simply never applied. Set spring.flyway.validate-migration-naming=true so Flyway fails fast instead.

A Flyway in 100 lines

The following program is a miniature migration tool running on in-memory H2. It has a history table with checksums, applies pending versioned scripts in order, re-runs repeatable scripts when they change, validates old scripts before doing anything, and supports a baseline. It tells the story of one project through five situations:

Java A miniature Flyway on H2

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.

Study the five stories. The first start creates everything and records three rows. The restart does nothing, because every checksum matches. Story 3 shows the two kinds of migration working together: only V3 is new, and the view is re-applied because its file changed (two REPEATABLE rows exist in the history, newest wins). Story 4 is the checksum safety net: the deployment refuses to start. Story 5 is the baseline: an existing database is declared to be "at version 2", so Flyway skips V1 and V2 (which would fail, since the tables already exist) and applies only V3 and the repeatable view.

Flyway in Spring Boot

In Spring Boot 4 the starter is spring-boot-starter-flyway; in earlier versions you add org.flywaydb:flyway-core and, for some databases, a module such as flyway-database-postgresql or flyway-mysql. Boot detects Flyway and runs migrate before the JPA EntityManagerFactory and your repositories start. No code is needed, only scripts and properties:

PROPERTIES
spring.flyway.enabled=true
spring.flyway.locations=classpath:db/migration
spring.flyway.validate-migration-naming=true

# Existing database without a history table:
spring.flyway.baseline-on-migrate=true
spring.flyway.baseline-version=2

# Let Hibernate verify, never change the schema:
spring.jpa.hibernate.ddl-auto=validate

With ddl-auto=validate, Hibernate checks at startup that the entities match the schema Flyway built, which catches mismatches early (see Hibernate Setup and Entities). Never combine Flyway with ddl-auto=update or create: two tools would fight over the same schema.

A typical migration is plain SQL for your database:

SQL
-- V4__add_loan_table.sql
CREATE TABLE loan (
    id          BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    book_id     BIGINT NOT NULL REFERENCES book(id),
    member_id   BIGINT NOT NULL,
    loaned_at   DATE   NOT NULL,
    returned_at DATE
);

CREATE INDEX idx_loan_book ON loan (book_id);

When SQL is not enough (for example, back-filling a column using application logic), write a Java migration: a class named like V5__BackfillSlugs that extends BaseJavaMigration and receives a JDBC connection in migrate(Context). It follows the same versioning rules.

The commands behind the magic

Flyway offers the same operations from Spring Boot startup, the Maven plugin, Gradle and a command-line tool:

Command What it does
migrate Applies pending migrations
info Prints every script with its state (pending, success, failed, outdated, ignored)
validate Compares applied checksums with the files; changes nothing
baseline Marks an existing database as being at a given version
repair Removes failed entries and realigns checksums with the current files
clean Drops everything in the schemas; disabled by default for good reason

repair is for emergencies, for example when a migration failed halfway on a database that cannot roll back DDL (MySQL commits each DDL statement immediately) and you cleaned up by hand. Using it to hide an edited script just moves the disagreement from Flyway into your database. Keep clean disabled (spring.flyway.clean-disabled=true, the default) so no misconfigured profile can wipe production.

Working with a team

  • Version collisions. Two branches both add V7__.... The second to merge fails in CI, and its author renumbers the file. Teams that dislike this use timestamp versions such as V20260310_1415__add_loan.sql.
  • Out of order. If a lower version appears after a higher one already ran, Flyway reports it as ignored and validation fails. spring.flyway.out-of-order=true allows applying it; use it sparingly, because environments may then run scripts in different orders.
  • Roll forward. Undo migrations exist only in paid Flyway editions, and most teams do not rely on them. To reverse a change, write a new migration that reverses it.
  • Safe changes with several instances. When a rolling deployment runs old and new code side by side, schema changes must work for both. Use the expand-and-contract approach from Deploying Java Applications: add the new column first, deploy code that writes both, back-fill, and drop the old column in a later release.
  • Concurrent startup. When three instances start together, Flyway takes a lock in the database, so one migrates and the others wait.
  • Long locks. ALTER TABLE on a huge table can block writes for minutes. Learn your database's online-DDL options and test migrations against production-sized data.
  • Test migrations. Build the schema from scratch in a test, and run it against the production database engine, not only H2, using Testcontainers as described in Integration Testing. Flyway's placeholders and callbacks (afterMigrate.sql) are available when you need environment-specific values.
  • Seed data. Reference data (countries, roles) belongs in migrations. Test data belongs in tests, never in files that run in production.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does Flyway fail at startup if you edit V2__add_published_year.sql after it has been applied?

    Flyway stores a checksum for every applied versioned migration and validates it before migrating. Add a new migration instead of editing an old one.
  2. 2. A folder contains V2__a.sql, V10__b.sql and V1__c.sql. In which order do they run?

    Versions are compared numerically, part by part, not as text.
  3. 3. What is a repeatable migration (R__name.sql) for?

    Repeatable migrations run after the versioned ones whenever their checksum differs from the last applied one.
  4. 4. You add Flyway to a production database that already has tables and no history. Which feature prevents V1 (create tables) from failing?

    With baseline-on-migrate and a baseline version, Flyway records a baseline row and applies only newer migrations.
  5. 5. Why combine Flyway with spring.jpa.hibernate.ddl-auto=validate instead of update?

    Two tools changing one schema would conflict. Validation catches entity and migration mismatches at startup.

Summary

  • Flyway applies versioned SQL scripts (V<version>__<description>.sql) once, in numeric order, and records each in a history table with a checksum.
  • Repeatable scripts (R__...) re-run whenever their content changes; they suit views and procedures.
  • Never edit an applied migration: validation compares checksums and stops the deployment. Fix mistakes with a new migration, and use repair only deliberately.
  • Use a baseline to bring an existing database under Flyway control; keep clean disabled in production.
  • Spring Boot runs Flyway at startup before JPA; pair it with ddl-auto=validate, turn on naming validation and test migrations on the real database engine.
  • Plan for team conflicts, long-running DDL and rolling deployments with expand-and-contract changes.

Next: Service Discovery starts the Spring Cloud chapter on how microservices find each other.