8.5 DB Migration (Flyway)
Use Flyway (or Liquibase) to version schema and data changes and apply them automatically on deploy.
Reference: Spring Boot 3.2.x, Flyway
1. Dependency
implementation 'org.flywaydb:flyway-core'
implementation 'org.flywaydb:flyway-mysql'
- Spring Boot auto-configures Flyway when flyway-core is on the classpath.
2. Script Location and Naming
Default path: src/main/resources/db/migration/
Naming: V{version}__{description}.sql
- V + version (e.g. 1, 2_0) + __ (double underscore) + description.
Examples: V1__create_members_table.sql, V2__add_email_to_members.sql
3. Script Example
V1__create_members_table.sql
CREATE TABLE members (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
V2__add_email_to_members.sql
ALTER TABLE members ADD COLUMN phone VARCHAR(20);
CREATE INDEX idx_members_email ON members(email);
- Applied versions are recorded in flyway_schema_history and not re-run.
4. application.yml
spring:
flyway:
enabled: true
locations: classpath:db/migration
baseline-on-migrate: true
- baseline-on-migrate: true: use when applying to an existing DB for the first time.
5. Disable in Tests
spring:
flyway:
enabled: false
6. Notes
- Do not change already-applied scripts; add new ones for fixes.
- Community edition has no undo; roll forward with new migrations.
tip
Standardize on Flyway (or Liquibase) so local, CI, and production share the same migration history.