Spring Boot: From Basics to Production · Persistence with Spring Data JPA

Schema Migrations with Flyway

Version the database schema and run migrations on startup or in CI/CD.

Add Flyway and put SQL migrations in src/main/resources/db/migration named V1__create_products.sql, V2__add_status.sql. Spring Boot runs pending migrations on startup (or run them as a separate deploy step), and with ddl-auto=validate Hibernate checks entities match the schema. Never edit applied migrations; write new ones, and keep changes backward compatible for rolling deploys.

-- src/main/resources/db/migration/V3__add_order_status.sql
ALTER TABLE orders ADD COLUMN status VARCHAR(20);
UPDATE orders SET status = 'PAID' WHERE status IS NULL;
ALTER TABLE orders ALTER COLUMN status SET NOT NULL;
CREATE INDEX idx_orders_status ON orders (status);
spring:
  jpa:
    hibernate:
      ddl-auto: validate
  flyway:
    enabled: true

Common pitfalls

  • Editing an applied migration (checksum mismatch, drift between environments).
  • Destructive changes in the same release that stops using a column.
  • Long-locking migrations on big tables during startup.

Key points

  • Versioned SQL migrations
  • ddl-auto=validate
  • Backward-compatible changes for rolling deploys

Further reading: Spring Boot: Flyway

Practice questions

What happens if you edit a migration that has already run?

Answer

Flyway detects a checksum mismatch and fails validation; environments would otherwise drift. Add a new migration instead.

Why combine Flyway with ddl-auto=validate?

Answer

Flyway owns schema changes, and Hibernate verifies at startup that entities match the schema, catching mapping mistakes early.

Open in the app to mark lessons complete, take notes and track your progress.