Skip to lesson

Seed data and repeatable migrations

A shop's database needs some rows before the app works, such as GST slabs, but fake customers must never reach production. A reporting view also changes often, and copying it into a new versioned file each time gets messy.

Reference data vs sample data

Reference data is a small, fixed set of rows the code depends on, such as GST slabs or order statuses. Every environment needs the same rows, so they go in a versioned migration.

Example 1 creates the gst_slabs table and fills it in V2__create_gst_slabs.sql, a normal versioned migration that runs everywhere.

Example 1 · V2__create_gst_slabs.sql: reference data for every environment

Runs in: seed-lab: a practice copy of shoplite-api with V1, the db/dev-data folder and MySQL

SQL
-- src/main/resources/db/migration/V2__create_gst_slabs.sql-- V2: GST slabs are reference data: every environment needs the same rows.CREATE TABLE gst_slabs (  rate        DECIMAL(4,2) NOT NULL PRIMARY KEY,  description VARCHAR(60)  NOT NULL);
INSERT INTO gst_slabs (rate, description) VALUES  (0.00,  'Nil rate'),  (5.00,  'Merit rate'),  (18.00, 'Standard rate'),  (40.00, 'Special rate');
Sample output
mysql> SELECT * FROM gst_slabs;        (on the prod-profile database)
+-------+---------------+
| rate  | description   |
+-------+---------------+
|  0.00 | Nil rate      |
|  5.00 | Merit rate    |
| 18.00 | Standard rate |
| 40.00 | Special rate  |
+-------+---------------+

What this code does

  • The table and its rows travel together in one versioned file, so no environment can have the table without the rows.
  • The rows are the GST rates in use since the September 2025 change (0, 5, 18 and 40 percent). When the government changes them, you add a new version with an UPDATE or INSERT; you never edit V2.
  • The output comes from the database started with the prod profile: reference data is there even where sample data is not.

Sample data is anything that only helps people try the app: the eight Section 12 customers, their orders, a test product called "USB-C Cable 1m". Production must never get these rows. Real customers would see fake orders, and a fake e-mail such as asha.rao@example.com would block a real sign-up with that address.

Without this split, either production starts with fake rows that someone deletes by hand, or every developer loads sample data with their own script and nobody has the same database.

A simple test: if deleting the rows breaks the app, they are reference data. If deleting them only makes the screens empty, they are sample data.

spring.flyway.locations per profile

spring.flyway.locations is the Spring setting that lists the folders Flyway scans for migrations. The default is classpath:db/migration; a profile can add more folders.

Example 2 keeps the sample rows in a second folder, db/dev-data, that only the dev profile adds. Example 3 shows what goes wrong on an old database.

Example 2 · application-dev.yml and db/dev-data: sample rows only in dev

Runs in: seed-lab: a practice copy of shoplite-api with V1, the db/dev-data folder and MySQL

YAML
# src/main/resources/application.yml (shared, also used by prod)spring:  flyway:    locations: classpath:db/migration# src/main/resources/application-dev.ymlspring:  flyway:    # the real migrations plus the Section 12 sample rows (dev only)    locations: classpath:db/migration,classpath:db/dev-data# src/main/resources/db/dev-data/V1_1__sample_data.sql (first lines)# -- Dev-only sample data: the Section 12 seed rows.# -- Lives in db/dev-data, which only the dev and test profiles add to spring.flyway.locations.# INSERT INTO customers (full_name, email, phone, created_at) VALUES#   ('Asha Rao', 'asha.rao@example.com', '9876543201', '2026-05-04 10:15:00'), ...
Sample output
$ mvn spring-boot:run        (dev profile, empty database shoplite_lab; log prefix trimmed)
INFO com.shoplite.ShopliteApiApplication : No active profile set, falling back to 1 default profile: "dev"
INFO o.f.core.internal.command.DbValidate : Successfully validated 3 migrations (execution time 00:00.048s)
INFO o.f.core.internal.command.DbMigrate : Current version of schema `shoplite_lab`: << Empty Schema >>
INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite_lab` to version "1 - create schema"
INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite_lab` to version "1.1 - sample data"
INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite_lab` to version "2 - create gst slabs"
INFO o.f.core.internal.command.DbMigrate : Successfully applied 3 migrations to schema `shoplite_lab`, now at version v2 (execution time 00:01.629s)

$ java -jar target/shoplite-api-1.0.0.jar --spring.profiles.active=prod        (empty database shoplite_prod_copy)
INFO com.shoplite.ShopliteApiApplication : The following 1 profile is active: "prod"
INFO o.f.core.internal.command.DbValidate : Successfully validated 2 migrations (execution time 00:00.051s)
INFO o.f.core.internal.command.DbMigrate : Current version of schema `shoplite_prod_copy`: << Empty Schema >>
INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite_prod_copy` to version "1 - create schema"
INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite_prod_copy` to version "2 - create gst slabs"
INFO o.f.core.internal.command.DbMigrate : Successfully applied 2 migrations to schema `shoplite_prod_copy`, now at version v2 (execution time 00:00.975s)

Row counts afterwards:
database            customers  products  orders  gst_slabs
shoplite_lab                8        15      16          4
shoplite_prod_copy          0         0       0          4

What this code does

  • The dev profile scans two folders, so Flyway finds three files and runs them in version order: 1, 1.1, 2. The prod profile scans one folder and never sees version 1.1.
  • Both databases end at version v2 with the same tables and the same four GST slabs; only dev has the 8 customers, 15 products and 16 orders.
  • Profile-specific files override application.yml, so application-dev.yml repeats classpath:db/migration. Forget it and dev would get the sample rows but no tables.

Example 3 · Sample data meets a database that already has it

Runs in: seed-lab: a practice copy of shoplite-api with V1, the db/dev-data folder and MySQL

Text
# shoplite_copy: built by hand from the Section 12 script (tables AND sample rows),# then baselined at version 1 in the Flyway setup lesson.# Now the app starts with the dev profile, which adds db/dev-data:mvn spring-boot:run
Sample output
INFO  o.f.core.internal.command.DbMigrate : Current version of schema `shoplite_copy`: 1
INFO  o.f.core.internal.command.DbMigrate : Migrating schema `shoplite_copy` to version "1.1 - sample data"
ERROR o.f.core.internal.command.DbMigrate : Migration of schema `shoplite_copy` to version "1.1 - sample data" failed! Please restore backups and roll back database and code!
...
Caused by: org.flywaydb.core.internal.exception.FlywayMigrateException: Failed to execute script V1_1__sample_data.sql
SQL State  : 23000
Error Code : 1062
Message    : Duplicate entry 'asha.rao@example.com' for key 'customers.uq_customers_email'
Location   : db/dev-data/V1_1__sample_data.sql (...)
Line       : 6

mysql> SELECT installed_rank, version, description, success FROM flyway_schema_history;
+----------------+---------+-----------------------+---------+
| installed_rank | version | description           | success |
+----------------+---------+-----------------------+---------+
|              1 | 1       | << Flyway Baseline >> |       1 |
|              2 | 1.1     | sample data           |       0 |
+----------------+---------+-----------------------+---------+

What this code does

  • Baseline 1 told Flyway "this database has V1", which was true for the tables but not the whole story: the sample rows were there too. So Flyway ran V1.1 and the first INSERT (line 6) hit the unique e-mail.
  • The UNIQUE constraint saved the data: the failed INSERT added no rows. The history now has a failed row, as in the previous lesson.
  • Fix for a dev database: drop it and let Flyway rebuild everything (DROP DATABASE shoplite_copy; CREATE DATABASE shoplite_copy;), or delete the history table and baseline at 1.1. The module project uses baseline-version: 1.1 for exactly this reason.

application.yml and application-prod.yml keep the default folder; application-dev.yml and the test settings add db/dev-data. Flyway merges all locations into one list sorted by version, so the sample file needs a version between the real ones: V1_1__sample_data.sql is version 1.1, after V1 (the tables) and before V2. Dev runs 1, 1.1, 2; production runs 1, 2. Gaps in the numbers are fine.

A database that already holds the sample rows but was baselined at version 1 gets V1.1 again, and MySQL rejects the duplicate e-mail. Baseline such a database at 1.1, because it already contains the sample rows, or drop the dev database and let Flyway rebuild it from scratch.

Predict the output

Which versions run where?

Production scans only db/migration. Dev scans db/migration and db/dev-data.

Round 1 of 2

Which versions does a fresh dev database run, in order?

db/migration: V1__create_schema.sql
V2__create_gst_slabs.sql
db/dev-data: V1_1__sample_data.sql

R__ repeatable migrations

A repeatable migration is a Flyway file named R__description.sql, with no version. Flyway runs it after all versioned migrations, and runs it again every time its checksum changes.

Example 4 keeps the order_totals view in R__order_totals_view.sql. Example 5 edits the file and starts the app again.

Example 4 · R__order_totals_view.sql: a view kept up to date

Runs in: seed-lab: a practice copy of shoplite-api with V1, the db/dev-data folder and MySQL

SQL
-- src/main/resources/db/migration/R__order_totals_view.sql-- Repeatable: Flyway reruns this file whenever its content changes.-- One row per order with its total, for reports and the admin screen.CREATE OR REPLACE VIEW order_totals ASSELECT o.order_id,       o.customer_id,       o.status,       o.ordered_at,       SUM(oi.quantity * oi.unit_price) AS totalFROM orders oJOIN order_items oi ON oi.order_id = o.order_idGROUP BY o.order_id, o.customer_id, o.status, o.ordered_at;
Sample output
first start after adding the file        (log prefix trimmed)
INFO o.f.core.internal.command.DbValidate : Successfully validated 4 migrations (execution time 00:00.100s)
INFO o.f.core.internal.command.DbMigrate : Current version of schema `shoplite_lab`: 2
INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite_lab` with repeatable migration "order totals view"
INFO o.f.core.internal.command.DbMigrate : Successfully applied 1 migration to schema `shoplite_lab` (execution time 00:00.053s)

mysql> SELECT * FROM order_totals WHERE customer_id = 2 ORDER BY ordered_at DESC;
+----------+-------------+-----------+---------------------+----------+
| order_id | customer_id | status    | ordered_at          | total    |
+----------+-------------+-----------+---------------------+----------+
|       14 |           2 | SHIPPED   | 2026-09-21 21:05:00 | 19298.00 |
|        7 |           2 | DELIVERED | 2026-08-09 11:00:00 |  1698.00 |
|        2 |           2 | DELIVERED | 2026-07-05 19:45:00 |  1947.00 |
+----------+-------------+-----------+---------------------+----------+

second start, file unchanged
INFO o.f.core.internal.command.DbMigrate : Current version of schema `shoplite_lab`: 2
INFO o.f.core.internal.command.DbMigrate : Schema `shoplite_lab` is up to date. No migration necessary.

What this code does

  • The log says "with repeatable migration" and no version: the current version stays 2. The totals match the API contract's order list for customer 2 (19298.00, 1698.00, 1947.00).
  • On the second start the checksum is the same, so Flyway skips the file. A repeatable runs only when you change it.
  • CREATE OR REPLACE is what makes rerunning safe. MySQL views are fine here because ShopLite never maps this view to an entity that validate would check.

Example 5 · Editing the repeatable: it runs again

Runs in: seed-lab: a practice copy of shoplite-api with V1, the db/dev-data folder and MySQL

SQL
-- R__order_totals_view.sql, edited in place: one new columnCREATE OR REPLACE VIEW order_totals ASSELECT o.order_id,       o.customer_id,       o.status,       o.ordered_at,       SUM(oi.quantity) AS item_count,       SUM(oi.quantity * oi.unit_price) AS totalFROM orders oJOIN order_items oi ON oi.order_id = o.order_idGROUP BY o.order_id, o.customer_id, o.status, o.ordered_at;
Sample output
INFO o.f.core.internal.command.DbValidate : Successfully validated 5 migrations (execution time 00:00.108s)
INFO o.f.core.internal.command.DbMigrate : Current version of schema `shoplite_lab`: 2
INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite_lab` with repeatable migration "order totals view"
INFO o.f.core.internal.command.DbMigrate : Successfully applied 1 migration to schema `shoplite_lab` (execution time 00:00.074s)

mysql> SELECT installed_rank, version, description, type, script, checksum FROM flyway_schema_history;
+----------------+---------+-------------------+------+--------------------------+------------+
| installed_rank | version | description       | type | script                   | checksum   |
+----------------+---------+-------------------+------+--------------------------+------------+
|              1 | 1       | create schema     | SQL  | V1__create_schema.sql    |  509004249 |
|              2 | 1.1     | sample data       | SQL  | V1_1__sample_data.sql    |  775330735 |
|              3 | 2       | create gst slabs  | SQL  | V2__create_gst_slabs.sql | -667829985 |
|              4 | NULL    | order totals view | SQL  | R__order_totals_view.sql |  830039031 |
|              5 | NULL    | order totals view | SQL  | R__order_totals_view.sql |  927727034 |
+----------------+---------+-------------------+------+--------------------------+------------+

What this code does

  • Editing a versioned file gives a checksum mismatch; editing a repeatable is the normal way to change it. Flyway sees the new checksum and reruns the file.
  • The history keeps both runs (rows 4 and 5, version NULL, different checksums), so you can see when the view changed.
  • Customer 2's orders now show item_count 2, 2 and 4 next to the same totals.

A view, a stored procedure or a reporting table suits a repeatable file, because you always rewrite it completely. The history table gets one row per run, with version NULL and the new checksum; an unchanged file is skipped. You keep one file per view and edit it in place, so Git diffs show the change, where versioned files would copy the whole view into V7, V12 and V19.

A repeatable script must run correctly on any database at any time, so it must replace, never add: CREATE VIEW without OR REPLACE fails on the second run with "Table 'order_totals' already exists".

Find the bug

Find the line that breaks a rerun

Both files are repeatable. Click the line that fails when Flyway runs the file a second time.

R__order_totals_view.sql runs again after an edit.

Round 1 of 2
Repeatables run in the order of their descriptions and always after the versioned ones. A view that needs a new column must wait for the versioned migration that adds it, which Flyway guarantees.

Callbacks: afterMigrate and others

A callback is code Flyway runs around its commands, such as beforeMigrate or afterMigrate. It can be an SQL file named after the event, or a Java bean that implements Callback.

Example 6 adds afterMigrate__refresh_statistics.sql, an SQL callback that Flyway runs after every migrate.

Example 6 · afterMigrate__refresh_statistics.sql: an SQL callback

Runs in: seed-lab: a practice copy of shoplite-api with V1, the db/dev-data folder and MySQL

SQL
-- src/main/resources/db/migration/afterMigrate__refresh_statistics.sql-- Runs after every migrate: refresh index statisticsANALYZE TABLE products, orders;
Sample output
INFO o.f.core.internal.command.DbMigrate : Current version of schema `shoplite_lab`: 2
INFO o.f.core.internal.command.DbMigrate : Schema `shoplite_lab` is up to date. No migration necessary.
INFO o.f.c.i.c.SqlScriptCallbackFactory : Executing SQL callback: afterMigrate - refresh statistics
INFO o.f.c.i.s.DefaultSqlScriptExecutor : +-----------------------+---------+----------+----------+
| Table                 | Op      | Msg_type | Msg_text |
+-----------------------+---------+----------+----------+
| shoplite_lab.products | analyze | status   | OK       |
| shoplite_lab.orders   | analyze | status   | OK       |
+-----------------------+---------+----------+----------+

What this code does

  • The file name is the event (afterMigrate), two underscores and a description. Flyway ran it although no migration was pending, and printed the result table of the statement.
  • ANALYZE TABLE refreshes the statistics MySQL uses to choose indexes, which is useful right after an index migration and harmless when repeated.
  • Callbacks are not migrations: no history row, no checksum check. Keep them small and safe to repeat; schema changes still belong in V files.

The event names include beforeMigrate, afterMigrate, afterMigrateError and beforeValidate. An SQL callback runs after every migrate, even when nothing was pending, so it must be safe to repeat, and it is not recorded in the history.

A Java callback is a Spring bean that implements org.flywaydb.core.api.callback.Callback; Spring Boot hands every such bean to Flyway. Practice 7 writes one that logs row counts in the dev profile. Flyway also supports Java migrations, a class such as V3__Backfill_pincodes extends BaseJavaMigration in a db.migration package, for changes too complex for SQL. ShopLite does not need one; plain SQL is easier to review.

Next step

Check your understanding

12 quick questions