Skip to lesson

Adding Flyway and writing V1

A new teammate clones ShopLite and the app will not start: the tables do not exist. Someone must run the right SQL scripts, in the right order, on every laptop, test server and production database.

Spring Boot 4: spring-boot-starter-flyway plus flyway-mysql

Flyway is a database migration tool. It runs versioned SQL scripts once per database, in order, and records each one in a table inside that database. With Spring Boot it runs at startup, before Hibernate.

Flyway needs two Maven dependencies on Spring Boot 4.1.1: spring-boot-starter-flyway and flyway-mysql. Boot manages both versions, so you write no <version> lines.

Example 1 · pom.xml: the Flyway starter and MySQL support

Runs in: the shoplite-api Spring Boot project

XML
<!-- pom.xml (the dependencies this lesson adds; Spring Boot 4.1.1 manages both versions) --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-flyway</artifactId></dependency><dependency>    <groupId>org.flywaydb</groupId>    <artifactId>flyway-mysql</artifactId></dependency>
Sample output
$ mvn dependency:tree -Dincludes=org.flywaydb,org.springframework.boot:spring-boot-flyway,org.springframework.boot:spring-boot-starter-flyway
[INFO] --- dependency:3.10.0:tree (default-cli) @ shoplite-api ---
[INFO] com.shoplite:shoplite-api:jar:1.0.0
[INFO] +- org.springframework.boot:spring-boot-starter-flyway:jar:4.1.1:compile
[INFO] |  \- org.springframework.boot:spring-boot-flyway:jar:4.1.1:compile
[INFO] \- org.flywaydb:flyway-mysql:jar:12.4.0:compile
[INFO]    \- org.flywaydb:flyway-core:jar:12.4.0:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS

What this code does

  • The starter brings spring-boot-flyway, the Boot 4 module that runs Flyway at startup; flyway-mysql brings flyway-core 12.4.0 with it.
  • No <version> lines: Spring Boot 4.1.1's parent sets flyway.version to 12.4.0, so the two Flyway jars always match.
  • spring-boot-starter-data-jpa, the MySQL driver and the web starter stay as they are.

spring-boot-starter-flyway brings Flyway (version 12.4.0) and the code that runs it at startup. flyway-mysql is Flyway's MySQL support: since Flyway 10, each database lives in its own module, so without it Flyway cannot talk to MySQL (the last section shows the error).

Boot 3 projects added only flyway-core. Boot 4 split its autoconfigure jar into one module per technology, and the Flyway module (spring-boot-flyway) comes with the starter. With only flyway-core on Boot 4, Flyway never runs: there is no Flyway line in the log, and Hibernate's validate stops the app with Schema validation: missing table [addresses].

db/migration and the naming rule V1__create_schema.sql

A versioned migration is a SQL file named V<version>__<description>.sql, such as V1__create_schema.sql. Flyway runs it exactly once per database, in version order.

Example 2 is ShopLite's V1__create_schema.sql. It lives in src/main/resources/db/migration, the folder Flyway scans by default.

Example 2 · src/main/resources/db/migration/V1__create_schema.sql

Runs in: the shoplite-api Spring Boot project

SQL
-- V1: the ShopLite schema from Section 12 (six tables, keys and checks).-- Flyway runs this once per database and records it in flyway_schema_history.-- Never edit this file after it has run anywhere: add a new V<n> file instead.
CREATE TABLE customers (  customer_id INT          NOT NULL AUTO_INCREMENT PRIMARY KEY,  full_name   VARCHAR(100) NOT NULL,  email       VARCHAR(255) NOT NULL,  phone       VARCHAR(15)  NULL,  created_at  DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,  CONSTRAINT uq_customers_email UNIQUE (email));
CREATE TABLE addresses (  address_id  INT          NOT NULL AUTO_INCREMENT PRIMARY KEY,  customer_id INT          NOT NULL,  label       VARCHAR(20)  NOT NULL DEFAULT 'Home',  line1       VARCHAR(150) NOT NULL,  city        VARCHAR(60)  NOT NULL,  state       VARCHAR(60)  NOT NULL,  pincode     CHAR(6)      NOT NULL,  is_default  BOOLEAN      NOT NULL DEFAULT FALSE,  CONSTRAINT fk_addresses_customer FOREIGN KEY (customer_id) REFERENCES customers (customer_id) ON DELETE CASCADE,  CONSTRAINT chk_addresses_pincode CHECK (pincode REGEXP '^[1-9][0-9]{5}$'));
CREATE TABLE categories (  category_id INT         NOT NULL AUTO_INCREMENT PRIMARY KEY,  name        VARCHAR(50) NOT NULL,  parent_id   INT         NULL,  CONSTRAINT uq_categories_name UNIQUE (name),  CONSTRAINT fk_categories_parent FOREIGN KEY (parent_id) REFERENCES categories (category_id));
CREATE TABLE products (  product_id  INT           NOT NULL AUTO_INCREMENT PRIMARY KEY,  sku         VARCHAR(20)   NOT NULL,  name        VARCHAR(120)  NOT NULL,  category_id INT           NOT NULL,  price       DECIMAL(10,2) NOT NULL,  stock       INT           NOT NULL DEFAULT 0,  is_active   BOOLEAN       NOT NULL DEFAULT TRUE,  CONSTRAINT uq_products_sku UNIQUE (sku),  CONSTRAINT fk_products_category FOREIGN KEY (category_id) REFERENCES categories (category_id),  CONSTRAINT chk_products_price CHECK (price > 0),  CONSTRAINT chk_products_stock CHECK (stock >= 0));
CREATE TABLE orders (  order_id    INT         NOT NULL AUTO_INCREMENT PRIMARY KEY,  customer_id INT         NOT NULL,  address_id  INT         NOT NULL,  status      VARCHAR(10) NOT NULL DEFAULT 'PLACED',  ordered_at  DATETIME    NOT NULL DEFAULT CURRENT_TIMESTAMP,  CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers (customer_id),  CONSTRAINT fk_orders_address FOREIGN KEY (address_id) REFERENCES addresses (address_id),  CONSTRAINT chk_orders_status CHECK (status IN ('PLACED', 'SHIPPED', 'DELIVERED', 'CANCELLED')));
CREATE TABLE order_items (  order_item_id INT           NOT NULL AUTO_INCREMENT PRIMARY KEY,  order_id      INT           NOT NULL,  product_id    INT           NOT NULL,  quantity      INT           NOT NULL,  unit_price    DECIMAL(10,2) NOT NULL,  CONSTRAINT uq_order_items_order_product UNIQUE (order_id, product_id),  CONSTRAINT fk_order_items_order FOREIGN KEY (order_id) REFERENCES orders (order_id) ON DELETE CASCADE,  CONSTRAINT fk_order_items_product FOREIGN KEY (product_id) REFERENCES products (product_id),  CONSTRAINT chk_order_items_quantity CHECK (quantity > 0),  CONSTRAINT chk_order_items_price CHECK (unit_price > 0));
Sample output
$ mysql -u root -p -e "CREATE DATABASE shoplite_flyway"
$ export DB_URL=jdbc:mysql://localhost:3306/shoplite_flyway     (PowerShell: $env:DB_URL = "...")
$ mvn spring-boot:run        (log prefix trimmed)
INFO org.flywaydb.core.FlywayExecutor : Database: jdbc:mysql://localhost:3306/shoplite_flyway (MySQL 8.4)
INFO o.f.c.i.s.JdbcTableSchemaHistory : Schema history table `shoplite_flyway`.`flyway_schema_history` does not exist yet
INFO o.f.core.internal.command.DbValidate : Successfully validated 1 migration (execution time 00:00.100s)
INFO o.f.c.i.s.JdbcTableSchemaHistory : Creating Schema History table `shoplite_flyway`.`flyway_schema_history` ...
INFO o.f.core.internal.command.DbMigrate : Current version of schema `shoplite_flyway`: << Empty Schema >>
INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite_flyway` to version "1 - create schema"
INFO o.f.core.internal.command.DbMigrate : Successfully applied 1 migration to schema `shoplite_flyway`, now at version v1 (execution time 00:01.582s)
INFO org.hibernate.orm.jpa : HHH008540: Processing PersistenceUnitInfo [name: default]
INFO j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
INFO com.shoplite.ShopliteApiApplication : Started ShopliteApiApplication in 35.563 seconds (process running for 37.372)

What this code does

  • The file is the Section 12 script's six CREATE TABLE statements, in the same order (parents before children), with comments saying it must never be edited once it has run.
  • On an empty database Flyway creates its history table, runs V1 and logs the new version, and only then does Hibernate start and validate the six tables.
  • The database is new and empty on purpose, so you can watch Flyway build everything. Your timings will differ.

The name is a capital V, the version, two underscores, then a description with single underscores for spaces. V1__create_schema.sql is version 1, description "create schema". Versions compare as numbers, part by part: V1_1__x.sql is version 1.1, and V10 comes after V9. Gaps are fine.

ShopLite's V1 is the Section 12 CREATE script, minus three lines: no CREATE DATABASE, no USE (Flyway works in the database from DB_URL) and no DROP TABLE (a migration builds forward, it never wipes). The seed rows get their own dev-only script in the Seed Data lesson.

A file that breaks the naming rule, such as V2_add_index.sql with one underscore, is not an error by default: Flyway simply skips it. The Practice lesson shows how to spot that.

The flyway_schema_history table

flyway_schema_history is the table Flyway creates in your database to remember what it ran: one row per migration, with its version, a checksum of the file and whether it succeeded.

Example 3 reads the history table after the first start, then starts the app a second time with nothing new.

Flyway compares the files in db/migration with the rows in flyway_schema_history. V1__create_schema.sql and V2__create_gst_slabs.sql already have a history row with a matching checksum, so Flyway skips them. V3__add_gst_rate.sql has no history row yet, so Flyway runs it now and records it.

Example 3 · Reading flyway_schema_history, and a second start

Runs in: the shoplite-api Spring Boot project

SQL
-- in the shoplite_flyway databaseSELECT installed_rank, version, description, type, script, checksum,       installed_by, installed_on, execution_time, successFROM flyway_schema_history;
Sample output
+----------------+---------+---------------+------+-----------------------+-----------+--------------+---------------------+----------------+---------+
| installed_rank | version | description   | type | script                | checksum  | installed_by | installed_on        | execution_time | success |
+----------------+---------+---------------+------+-----------------------+-----------+--------------+---------------------+----------------+---------+
|              1 | 1       | create schema | SQL  | V1__create_schema.sql | 509004249 | root         | 2026-10-16 12:44:45 |           1582 |       1 |
+----------------+---------+---------------+------+-----------------------+-----------+--------------+---------------------+----------------+---------+

$ mvn spring-boot:run        (second start, log prefix trimmed)
INFO org.flywaydb.core.FlywayExecutor : Database: jdbc:mysql://localhost:3306/shoplite_flyway (MySQL 8.4)
INFO o.f.core.internal.command.DbValidate : Successfully validated 1 migration (execution time 00:00.170s)
INFO o.f.core.internal.command.DbMigrate : Current version of schema `shoplite_flyway`: 1
INFO o.f.core.internal.command.DbMigrate : Schema `shoplite_flyway` is up to date. No migration necessary.

What this code does

  • One row per applied script. checksum is a number computed from the file's content; execution_time is in milliseconds; success 1 means it finished.
  • On the second start Flyway validates V1 against its checksum, finds nothing new and runs nothing. That is why a migration runs exactly once per database.
  • Your installed_on and execution_time will differ. The checksum stays 509004249 as long as your V1 file is byte for byte the same as this one.

Each row also stores the description, the script name, who ran it, when and how long it took. At every start Flyway reads the table, compares it with the files, checks that each applied file's checksum (a number computed from the file's content) still matches, and runs only the new ones, in version order. When nothing is new, the log says "Schema shoplite_flyway is up to date. No migration necessary."

Never edit this table by hand to "fix" something. The Evolving lesson shows the safe tools for a broken history: undo the half change, then flyway repair.

Order of execution

What happens at one startup?

Tap the steps in the order they happen when the app starts.

An existing database: baseline-on-migrate and baseline-version

A baseline tells Flyway that a database already contains everything up to version N, so it starts from there. You need one for a database that existed before Flyway.

Example 4 starts Flyway on the old Section 12 database and gets an error. Example 5 baselines that database at version 1.

Example 4 · Flyway meets the old Section 12 database

Runs in: the shoplite-api Spring Boot project

Terminal
# shoplite_copy: a copy of the Section 12 shoplite database (tables + seed rows, no Flyway yet)export DB_URL=jdbc:mysql://localhost:3306/shoplite_copymvn spring-boot:run
Sample output
INFO org.flywaydb.core.FlywayExecutor : Database: jdbc:mysql://localhost:3306/shoplite_copy (MySQL 8.4)
INFO o.f.c.i.s.JdbcTableSchemaHistory : Schema history table `shoplite_copy`.`flyway_schema_history` does not exist yet
INFO o.f.core.internal.command.DbValidate : Successfully validated 1 migration (execution time 00:00.050s)
WARN ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' ...: Failed to initialize dependency 'flywayInitializer' of LoadTimeWeaverAware bean 'entityManagerFactory' ...
ERROR o.s.boot.SpringApplication : Application run failed
...
Caused by: org.flywaydb.core.api.FlywayException: Found non-empty schema(s) `shoplite_copy` but no schema history table. Use baseline() or set baselineOnMigrate to true to initialize the schema history table.

What this code does

  • The database has tables but no flyway_schema_history, so Flyway cannot know whether V1 already ran. It stops instead of guessing.
  • Making the copy: mysqldump -u root -p shoplite > shoplite.sql, CREATE DATABASE shoplite_copy, then mysql -u root -p shoplite_copy < shoplite.sql.
  • Spring calls Flyway's setting spring.flyway.baseline-on-migrate; the message uses Flyway's own name, baselineOnMigrate.

Example 5 · Baselining the existing database at version 1

Runs in: the shoplite-api Spring Boot project

Terminal
# One start with the two baseline settings, given on the command line (not committed)mvn spring-boot:run -Dspring-boot.run.arguments="--spring.flyway.baseline-on-migrate=true --spring.flyway.baseline-version=1"# then, in MySQLSELECT installed_rank, version, description, type, script, checksum, successFROM flyway_schema_history;
Sample output
INFO o.f.c.i.s.JdbcTableSchemaHistory : Schema history table `shoplite_copy`.`flyway_schema_history` does not exist yet
INFO o.f.core.internal.command.DbValidate : Successfully validated 1 migration (execution time 00:00.066s)
INFO o.f.c.i.s.JdbcTableSchemaHistory : Creating Schema History table `shoplite_copy`.`flyway_schema_history` with baseline ...
INFO o.f.core.internal.command.DbBaseline : Successfully baselined schema with version: 1
INFO o.f.core.internal.command.DbMigrate : Current version of schema `shoplite_copy`: 1
INFO o.f.core.internal.command.DbMigrate : Schema `shoplite_copy` is up to date. No migration necessary.
INFO com.shoplite.ShopliteApiApplication : Started ShopliteApiApplication in 24.262 seconds (process running for 26.329)

+----------------+---------+-----------------------+----------+-----------------------+----------+---------+
| installed_rank | version | description           | type     | script                | checksum | success |
+----------------+---------+-----------------------+----------+-----------------------+----------+---------+
|              1 | 1       | << Flyway Baseline >> | BASELINE | << Flyway Baseline >> |     NULL |       1 |
+----------------+---------+-----------------------+----------+-----------------------+----------+---------+

What this code does

  • Flyway creates the history table with one BASELINE row for version 1 and does not run V1, so the existing tables and rows are untouched.
  • From now on this database behaves like one Flyway built: a new V2 file runs on the next start. Further starts need no baseline settings.
  • Pick the version that matches what the database really contains. Here it holds exactly V1's tables, so the baseline is 1.

Without a baseline, Flyway refuses to touch a non-empty database that has no history table, because running V1 there would fail on "table already exists". spring.flyway.baseline-on-migrate=true creates the history table with a single BASELINE row instead; spring.flyway.baseline-version says which version that row stands for (default 1). Migrations up to that version are skipped; later ones run as usual.

Pass both as command-line arguments for the one start that baselines, instead of committing them: left on, they can hide a mistake such as pointing the app at the wrong, non-empty database. Try this on a copy of your data first; the module project baselines your real dev database.

Setup errors: Unsupported Database: MySQL

Example 6 removes flyway-mysql from the pom and shows the error Flyway then prints.

Example 6 · pom.xml without flyway-mysql

Runs in: a copy of the shoplite-api project

XML
<!-- the starter alone: Flyway runs, but has no MySQL support --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-flyway</artifactId></dependency><!-- flyway-mysql is missing here -->
Sample output
$ mvn spring-boot:run        (log prefix trimmed)
ERROR o.s.boot.SpringApplication : Application run failed
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/flyway/autoconfigure/FlywayAutoConfiguration$FlywayConfiguration.class]: Unsupported Database: MySQL 8.4
Caused by: org.flywaydb.core.api.FlywayException: Unsupported Database: MySQL 8.4
	at org.flywaydb.core.internal.database.DatabaseTypeRegister.lambda$getDatabaseTypeForConnection$5(DatabaseTypeRegister.java:129) ~[flyway-core-12.4.0.jar!/:na]

What this code does

  • Flyway connects, reads the server's name and version, and finds no module that supports it. The version in the message is your server's.
  • The fix is one dependency, org.flywaydb:flyway-mysql, with no version: Spring Boot keeps it in step with flyway-core.
  • The class path org/springframework/boot/flyway/autoconfigure/... shows Boot 4's separate Flyway module at work; on Boot 4 you get it from spring-boot-starter-flyway.

The error Unsupported Database: MySQL 8.4 means Flyway runs but has no MySQL module: add org.flywaydb:flyway-mysql (no version; Boot manages it). The app stops before Hibernate starts. Read Flyway errors from the bottom: the last Caused by: line is the real message. Spring wraps it in "Error creating bean with name 'flywayInitializer'", and Hibernate's bean says "Failed to initialize dependency 'flywayInitializer'": proof that the entity manager waits for Flyway.

The four setup errors and their fixes:

  • No Flyway lines in the log at all, then missing table → only flyway-core on Boot 4: use spring-boot-starter-flyway
  • Unsupported Database: MySQL → add flyway-mysql
  • Found non-empty schema(s) ... but no schema history table → baseline the existing database
  • Table 'customers' already exists → V1 ran against an old database; it should have been baselined

Fix the error

Fix the Flyway dependency

Read the real error, then pick the line that fixes the pom.

Round 1 of 2

Boot 4 app: Flyway never runs and no tables are created.

<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>

Error

Schema validation: missing table [addresses]

Next step

Check your understanding

11 quick questions