Managing Database Migrations
1. Configuring Flyway Migration Tool
| Property | Description |
|---|---|
spring.flyway.enabled |
Default true if on classpath |
spring.flyway.locations |
classpath:db/migration |
spring.flyway.baseline-on-migrate |
For existing DBs |
spring.flyway.schemas |
Target schemas |
spring.flyway.placeholders.* |
SQL placeholders |
2. Creating Flyway Migration Scripts
| Naming | Type |
|---|---|
V1__create_users.sql |
Versioned (run once) |
V1.1__add_email_index.sql |
Sub-version |
R__refresh_views.sql |
Repeatable (re-run on change) |
U1__rollback.sql |
Undo (Teams edition) |
Example: Flyway migration: create users table
-- V1__create_users.sql
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
3. Using Flyway Callbacks and Placeholders
| Callback | Fires |
|---|---|
beforeMigrate |
Before any migration |
afterMigrate |
After all complete |
afterEachMigrate |
After each script |
afterMigrateError |
On failure |
Example: Flyway schema placeholder
-- placeholders: ${app.schema}
CREATE SCHEMA IF NOT EXISTS ${app.schema};
4. Configuring Liquibase Migration Tool
| Property | Default |
|---|---|
spring.liquibase.change-log |
classpath:/db/changelog/db.changelog-master.yaml |
spring.liquibase.contexts |
CSV of contexts |
spring.liquibase.labels |
Label expression |
spring.liquibase.default-schema |
Schema target |
5. Creating Liquibase Changesets
Example: Liquibase changeset for users table
databaseChangeLog:
- changeSet:
id: 001-create-users
author: alice
changes:
- createTable:
tableName: users
columns:
- column: { name: id, type: BIGINT, autoIncrement: true,
constraints: { primaryKey: true } }
- column: { name: email, type: VARCHAR(255),
constraints: { nullable: false, unique: true } }
6. Using Liquibase Contexts and Labels
| Element | Purpose |
|---|---|
context: dev,test |
Run only in given contexts |
labels: feature-x,seed |
Tag-based filtering |
--contexts="dev" |
CLI selection |
7. Rolling Back Migrations (Liquibase)
| Command | Action |
|---|---|
liquibase rollbackCount 1 |
Undo last N |
liquibase rollback <tag> |
Roll back to tag |
liquibase rollbackToDate |
By timestamp |
8. Validating Migration Scripts
| Tool | Command |
|---|---|
| Flyway | mvn flyway:validate — checksums must match |
| Liquibase | liquibase validate |
| Boot | Fails fast at startup if checksum mismatch |
9. Using Baseline on Existing Databases
Example: Flyway baseline for existing schema
spring:
flyway:
baseline-on-migrate: true
baseline-version: 1
baseline-description: "Existing schema baseline"
10. Generating DDL from JPA Entities
| Value | Effect |
|---|---|
none |
Production default |
validate |
Verify schema matches |
update |
Apply non-destructive changes (dev only) |
create |
Drop + create on startup |
create-drop |
Above + drop on shutdown |
Warning: Use
validate in production; manage schema with
Flyway/Liquibase.