17 · Tests and migrations / LESSON 87 OF 102
Version the database schema
Schema changes need history and repeatable rollout.
Before this lesson: Integration tests and API contracts
Understand the topic
Add Flyway support and its PostgreSQL module using versions managed by your selected Boot release. Put versioned SQL in db/migration. Start V1 on a clean local database; do not blindly create tables already present.
Set spring.jpa.hibernate.ddl-auto=validate. Use one schema-management mechanism. Never edit an applied migration; add the next version. If ownership was already added, include its column and constraints in a follow-up migration.
EXAMPLE · SQL
src/main/resources/db/migration/V1__create_task.sql
CREATE TABLE task (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
title VARCHAR(120) NOT NULL,
done BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE INDEX idx_task_done_id ON task(done, id);What to expect
Flyway applies V1 once and records it in history. Hibernate validates the schema rather than changing it.
YOUR TURN
Put it into practice
- 01Replace create-drop with validate.
- 02Add V2 and test both a fresh and existing database.
- 03Check records survive an application restart.
Pass a quiz or complete a lab to check today’s streak. Each lesson counts once per day, including when you review it later.
UNDER THE HOOD
Build the mental model
Treat schema evolution as an ordered history shared by every environment.
- 01Checksums detect edits to applied migrations. Changing history creates disagreement between environments; add a new migration instead.
- 02Use an expand-and-contract rollout for breaking changes: introduce a compatible schema, deploy compatible code, backfill, then remove the old shape later.
- 03Backups are useful only if restore has been tested. A destructive migration cannot be made safe merely by naming a rollback file.
A mistake worth avoiding
Do not combine Hibernate schema mutation and Flyway ownership of the same schema in production.
DEBUGGING ROOM
Something broke. Where do you look?
A deployment reports a migration checksum mismatch.
Before revealing the diagnosis, write down your first investigation step.
CHECK YOUR UNDERSTANDING
An already-applied migration needs a new column. What should you do?
BUILD IT YOURSELF
Practise a compatible schema change
- 1.Add a nullable description column.
- 2.Deploy code that can handle old rows.
- 3.Backfill before adding a required constraint.
Acceptance checklist
Lab completion is your self-report. Knowledge checks do not certify project quality.
RETRIEVE IT FROM MEMORY
What makes a schema rollout backward compatible?
Revisit this lesson in three days after a successful check or lab.
Ready for the next step?
Explain ordering, checksums, and immutable migration history.
Reading is separate from passing a knowledge check or completing a lab.