Database Migrations with Flyway
Letting Hibernate create tables (ddl-auto=create) is convenient while learning, but dangerous in production: it cannot safely rename a column, migrate data, or tell you what changed. Real projects keep the schema in versioned SQL migration scripts that run in order, exactly once per database. Flyway is the most popular tool for this, and Spring Boot runs it automatically at startup.
Setup
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<!-- database-specific module, required for PostgreSQL, MySQL, etc. -->
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-database-postgresql</artifactId>
</dependency>Versions are managed by Spring Boot. Then tell Hibernate to stop generating the schema and only check it:
spring.jpa.hibernate.ddl-auto=validateWith validate, startup fails if an entity does not match the tables — a great safety net.
Writing migrations
Migrations live in src/main/resources/db/migration and follow a strict naming pattern: V<version>__<description>.sql (two underscores).
src/main/resources/db/migration/
├── V1__create_projects_and_tasks.sql
├── V2__add_task_priority.sql
└── V3__backfill_priority.sql-- V1__create_projects_and_tasks.sql
CREATE TABLE projects (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL UNIQUE
);
CREATE TABLE tasks (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
project_id BIGINT NOT NULL REFERENCES projects (id),
title VARCHAR(120) NOT NULL,
done BOOLEAN NOT NULL DEFAULT FALSE,
due_date DATE,
version BIGINT NOT NULL DEFAULT 0
);
CREATE INDEX idx_tasks_project ON tasks (project_id);-- V2__add_task_priority.sql
ALTER TABLE tasks ADD COLUMN priority VARCHAR(10);-- V3__backfill_priority.sql
UPDATE tasks SET priority = 'MEDIUM' WHERE priority IS NULL;
ALTER TABLE tasks ALTER COLUMN priority SET NOT NULL;Splitting V2 and V3 shows a common pattern: add a nullable column, fill it, then add the constraint.
What happens at startup
./mvnw spring-boot:run | grep -i flyway2025-10-16T11:02:40.611+07:00 INFO 53120 --- [tasks] [ main] org.flywaydb.core.FlywayExecutor : Database: jdbc:postgresql://localhost:5432/tasks (PostgreSQL 17.5)
2025-10-16T11:02:40.698+07:00 INFO 53120 --- [tasks] [ main] o.f.c.i.s.JdbcTableSchemaHistory : Schema history table "public"."flyway_schema_history" does not exist yet
2025-10-16T11:02:40.703+07:00 INFO 53120 --- [tasks] [ main] o.f.core.internal.command.DbValidate : Successfully validated 3 migrations (execution time 00:00.021s)
2025-10-16T11:02:40.731+07:00 INFO 53120 --- [tasks] [ main] o.f.c.i.s.JdbcTableSchemaHistory : Creating Schema History table "public"."flyway_schema_history" ...
2025-10-16T11:02:40.802+07:00 INFO 53120 --- [tasks] [ main] o.f.core.internal.command.DbMigrate : Current version of schema "public": << Empty Schema >>
2025-10-16T11:02:40.815+07:00 INFO 53120 --- [tasks] [ main] o.f.core.internal.command.DbMigrate : Migrating schema "public" to version "1 - create projects and tasks"
2025-10-16T11:02:40.861+07:00 INFO 53120 --- [tasks] [ main] o.f.core.internal.command.DbMigrate : Migrating schema "public" to version "2 - add task priority"
2025-10-16T11:02:40.874+07:00 INFO 53120 --- [tasks] [ main] o.f.core.internal.command.DbMigrate : Migrating schema "public" to version "3 - backfill priority"
2025-10-16T11:02:40.893+07:00 INFO 53120 --- [tasks] [ main] o.f.core.internal.command.DbMigrate : Successfully applied 3 migrations to schema "public", now at version v3 (execution time 00:00.092s)
Flyway records each applied script in the flyway_schema_history table, including a checksum of its content. On the next start it applies only scripts with a higher version:
psql -d tasks -c "select version, description, success from flyway_schema_history order by installed_rank" version | description | success
---------+---------------------------+---------
1 | create projects and tasks | t
2 | add task priority | t
3 | backfill priority | t
(3 rows)
The algorithm in plain Java
Flyway's core logic is small: sort scripts by version, skip the applied ones, verify checksums of applied scripts, run the rest in order. Here is that logic, including what happens when someone edits an already-applied migration:
import java.util.*;
record Migration(int version, String description, String sql) {
int checksum() { return sql.hashCode(); }
}
record Applied(int version, int checksum) {}
class MiniFlyway {
final List<Applied> history = new ArrayList<>();
void migrate(List<Migration> scripts) {
List<Migration> sorted = scripts.stream().sorted(Comparator.comparingInt(Migration::version)).toList();
for (Applied a : history) {
Migration m = sorted.stream().filter(s -> s.version() == a.version()).findFirst().orElseThrow();
if (m.checksum() != a.checksum()) {
throw new IllegalStateException("Validate failed: Migration checksum mismatch for migration version " + a.version());
}
}
int current = history.isEmpty() ? 0 : history.get(history.size() - 1).version();
int count = 0;
for (Migration m : sorted) {
if (m.version() <= current) continue;
System.out.println(" Migrating to version \"" + m.version() + " - " + m.description() + "\"");
history.add(new Applied(m.version(), m.checksum()));
count++;
}
System.out.println(" applied " + count + ", now at version v" +
(history.isEmpty() ? 0 : history.get(history.size() - 1).version()));
}
}
class Main {
public static void main(String[] args) {
MiniFlyway flyway = new MiniFlyway();
List<Migration> scripts = new ArrayList<>(List.of(
new Migration(2, "add task priority", "ALTER TABLE tasks ADD COLUMN priority VARCHAR(10);"),
new Migration(1, "create tables", "CREATE TABLE tasks (...);")));
System.out.println("first start:");
flyway.migrate(scripts);
System.out.println("second start, nothing new:");
flyway.migrate(scripts);
scripts.add(new Migration(3, "backfill priority", "UPDATE tasks SET priority = 'MEDIUM';"));
System.out.println("after adding V3:");
flyway.migrate(scripts);
scripts.set(0, new Migration(2, "add task priority", "ALTER TABLE tasks ADD COLUMN priority VARCHAR(20);"));
System.out.println("after editing V2:");
try {
flyway.migrate(scripts);
} catch (IllegalStateException e) {
System.out.println(" " + e.getMessage());
}
}
}first start:
Migrating to version "1 - create tables"
Migrating to version "2 - add task priority"
applied 2, now at version v2
second start, nothing new:
applied 0, now at version v2
after adding V3:
Migrating to version "3 - backfill priority"
applied 1, now at version v3
after editing V2:
Validate failed: Migration checksum mismatch for migration version 2
Note: Never edit a migration that has run anywhere outside your laptop. The checksum check will stop every other environment from starting. Fix mistakes with a new migration (
V4__fix_priority_length.sql).
Useful settings
| Property | Purpose |
|---|---|
spring.flyway.enabled |
turn migrations off (e.g. in some tests) |
spring.flyway.locations |
where scripts live (default classpath:db/migration) |
spring.flyway.baseline-on-migrate |
adopt an existing database that has no history table |
spring.flyway.clean-disabled |
default true; keeps clean (drop everything) from running by accident |
Flyway or Liquibase?
Spring Boot supports both. Flyway uses plain SQL files and is simple to learn; Liquibase describes changes in XML/YAML/JSON (or SQL) and can generate rollbacks. Pick one per project — the principles (versioned, immutable, ordered changes stored in Git) are identical.
Tip: Run the same migrations in your tests (Testcontainers with a real PostgreSQL works well) so the schema you test against is exactly the one production gets.
Test yourself
Which file name is a valid Flyway versioned migration?
V1_create_tasks.sqlV1__create_tasks.sql1-create-tasks.sqlcreate_tasks_V1.sql
You need to change a column of a migration already applied in production. What should you do?
- Edit the original script
- Delete the history table
- Add a new migration with a higher version
- Set ddl-auto=update
Which ddl-auto value fits best when Flyway manages the schema?
create-dropupdatevalidatecreate