Video in progress
How do Flyway migrations work in Spring Boot, and what rules do you follow with migration files?
With flyway-core added, Spring Boot runs the V1__...sql files from the db/migration folder in order at startup and records the result in the flyway_schema_history table. You never edit an applied file; you add a new version.
📖 Answer
The flow is simple: while the application starts, Flyway reads the flyway_schema_history table, sees which versions have been applied and runs the rest one after another. This happens before JPA, so Hibernate connects to a ready schema.
src/main/resources/db/migration/
V1__init.sql
V2__add_orders.sql
V3__index_orders_created_at.sql
On a team, these are the rules I look at:
- Don't touch an applied file. Flyway stores a checksum for each file; if you change it, the next startup fails validation. To fix a mistake, you write a new
V4__fix.... - Version collisions. If two developers create
V5in parallel, there's a problem after the merge. That's why some teams use a timestamp instead of a version:V20261103_1200__.... - Backward-compatible changes. Don't drop or rename a column in one step: the old version may still be running.
- An index on a big table. In PostgreSQL
CREATE INDEX CONCURRENTLYdoesn't work inside a transaction; such a migration has to be done separately. - Set
spring.jpa.hibernate.ddl-auto=validateto check at startup that the entities match the schema.
The tests run the same migrations too, so the test schema doesn't differ from prod.
Sign up to mark studied questions and save your progress.