Sub topic 2
Adding Flyway to a Spring Boot Project
This chapter shows how to add Flyway to a Spring Boot application, which dependencies you need, where migration files go, and how to confirm that Flyway ran. It assumes you know Spring Boot starters, application.yml, Maven or Gradle dependencies, basic SQL DDL, and have a PostgreSQL database you can connect to. Later chapters cover migration naming, the history table, and configuration in more detail. Here the goal is a working setup.
What Flyway does in this setup
Flyway is a library that applies SQL (or Java) migration files to a database in version order and records each one it applied. Spring Boot detects Flyway on the classpath and runs it automatically when the application starts, before the rest of your code uses the database.
You add three things:
- The Flyway dependencies.
- A datasource configuration, which you probably already have.
- A folder of migration files in
src/main/resources/db/migration.
No @EnableFlyway annotation or manual bean is needed. Spring Boot's FlywayAutoConfiguration creates and runs the Flyway object when it finds flyway-core and a DataSource.
Adding the dependencies
Two artifacts are needed for PostgreSQL. flyway-core contains the engine. Recent Flyway versions (10 and later) moved database-specific support into separate modules, so you also need flyway-database-postgresql. Without it, Flyway fails at startup with an error saying it found no support for your database type.
Spring Boot's dependency management supplies the versions, so you leave out the <version> element.
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-database-postgresql</artifactId>
</dependency>In Gradle, the equivalent lines are implementation 'org.flywaydb:flyway-core' and implementation 'org.flywaydb:flyway-database-postgresql'.
You also need the JDBC driver and a data access starter. A typical pom.xml already has spring-boot-starter-data-jpa and org.postgresql:postgresql.
Configuring the datasource
Flyway uses the application's DataSource by default, so your existing connection settings apply.
spring:
datasource:
url: jdbc:postgresql://localhost:5432/appdb
username: app
password: ${DB_PASSWORD}Keep the password in an environment variable or a secret store, not in the file. The database appdb must already exist. Flyway creates tables inside a database, but it does not create the database itself.
Choosing who owns the schema
Once Flyway is present, it should be the only thing that changes the schema. If Hibernate is also set to create or update tables, the two tools will disagree about what the schema looks like. The usual setup is to let Flyway own the schema and have Hibernate only check it.
spring:
flyway:
enabled: true
locations: classpath:db/migration
validate-on-migrate: true
jpa:
hibernate:
ddl-auto: validateWith ddl-auto: validate, Hibernate compares your entities to the existing tables at startup and fails if a column or table is missing. It never changes anything. enabled: true and locations: classpath:db/migration are already the defaults, and they are written out here so the setup is visible. validate-on-migrate: true makes Flyway check applied migrations against the files on disk before it applies new ones. A later chapter explains this check.
Writing the first migration
Flyway looks for files in the configured location. A versioned migration is named V<version>__<description>.sql. The prefix is an uppercase V, then the version number, then two underscores, then a description. Underscores in the description are shown as spaces in Flyway's output.
Create this file:
-- src/main/resources/db/migration/V1__create_app_user.sql
CREATE TABLE app_user (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
username VARCHAR(100) NOT NULL UNIQUE,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);Flyway applies this file once. If you start the application again, it sees that version 1 is already recorded and skips it.
To change the table, you add a new file with a higher version. You do not edit V1.
-- src/main/resources/db/migration/V2__add_display_name.sql
ALTER TABLE app_user ADD COLUMN display_name VARCHAR(200);The matching entity maps both columns:
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "app_user")
public class AppUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true, length = 100)
private String username;
@Column(name = "display_name", length = 200)
private String displayName;
protected AppUser() {
}
public AppUser(String username) {
this.username = username;
}
public Long getId() { return id; }
public String getUsername() { return username; }
public String getDisplayName() { return displayName; }
public void setDisplayName(String displayName) { this.displayName = displayName; }
}The created_at column is not mapped. Hibernate's validation only checks that mapped columns exist, so extra columns in the table are allowed.
Startup order
The order matters because Hibernate validation needs the tables to exist. Spring Boot arranges for Flyway to run before the EntityManagerFactory is created.
If a migration fails, the application does not start. This is intended. Running new code against a half-migrated schema is worse than not running.
Verifying that it worked
Start the application with mvn spring-boot:run. The log shows lines similar to these (exact wording varies by version):
Flyway Community Edition ... by Redgate
Database: jdbc:postgresql://localhost:5432/appdb (PostgreSQL 16.2)
Successfully validated 2 migrations
Creating Schema History table "public"."flyway_schema_history" ...
Migrating schema "public" to version "1 - create app user"
Migrating schema "public" to version "2 - add display name"
Successfully applied 2 migrations to schema "public", now at version v2You can also query the history table directly:
SELECT installed_rank, version, description, success
FROM flyway_schema_history
ORDER BY installed_rank;Flyway creates this table on first run. The next chapters cover its columns in detail. For now, a row with success = true for each version confirms that Flyway applied it.
Common setup errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `No database found to handle jdbc:postgresql:...` | `flyway-database-postgresql` is missing (Flyway 10 or later) | Add the module to the build |
| Application starts but no tables appear | Files are in the wrong folder, or the name does not match the pattern | Check the path `src/main/resources/db/migration` and that the name uses `V`, a version, two underscores, and `.sql` |
| `Schema-validation: missing table` | A migration did not run, or the entity names a different table | Check the log for applied migrations and the `@Table` name |
| `Found non-empty schema(s) ... but no schema history table` | The database already has tables and Flyway has no baseline | See the chapter on adopting Flyway on an existing database |
| `Migration checksum mismatch` | An applied migration file was edited | Restore the file and add a new migration instead |
A migration file that does not match the naming pattern is not always reported as an error. Flyway can silently ignore a file whose name it does not recognize, so a typo such as a single underscore (V1_create_app_user.sql) can lead to a table that never gets created. Always check the log for the number of migrations applied.
Summary of the setup
- Add
flyway-core, plusflyway-database-postgresqlfor PostgreSQL on Flyway 10 or later. - Keep the existing datasource settings.
- Put migration files in
src/main/resources/db/migration. - Set
spring.jpa.hibernate.ddl-autotovalidate. - Change the schema only by adding new, higher-numbered migrations.
Exercise
You add V1_create_orders.sql (one underscore) to src/main/resources/db/migration, start the application, and see no orders table. Flyway reports "Successfully validated 0 migrations". What is wrong, and how do you fix it?
Show answer
The file name does not match the versioned migration pattern, which needs two underscores between the version and the description. Flyway does not recognize the file as a migration, so it ignores it. Rename the file to V1__create_orders.sql and restart. The log should then report that it applied 1 migration.
Exercise
A teammate sets spring.jpa.hibernate.ddl-auto: update "to save time" while Flyway is enabled. Give two problems this causes and say which setting to use instead.
Show answer
Hibernate can create or alter tables without Flyway recording it, so the schema in each environment can differ and the history table no longer describes the real schema. A later Flyway migration may also fail because the object it creates already exists. Use ddl-auto: validate so Hibernate only checks the schema and Flyway remains the only tool that changes it.