Liquibase database migrations with Spring Boot

Liquibase describes schema changes as changesets in a changelog, written in YAML, XML, JSON or SQL, and records each one it applies. Because many changes are described rather than written as raw SQL, Liquibase can also undo them. This page runs a changelog under Spring Boot, then tags, previews and rolls back a release, filters changes by context, and shows what an edited changeset does.

Contents

How Liquibase works

Liquibase solves the same problem as Flyway: getting every database through the same schema changes, in the same order, exactly once. Its unit of change is the changeset, identified by an id, an author and the file it is in. Changesets live in a changelog, and a master changelog usually includes the others in order.

Two tables in the target database hold Liquibase's state:

  • DATABASECHANGELOG: one row per applied changeset, with its id, author, file, execution order, type and an MD5-based checksum. A changeset whose id, author and file are already in the table is skipped.
  • DATABASECHANGELOGLOCK: a single-row lock. The process that migrates sets it, so that several application instances starting together do not run the same changes twice.

The main difference from Flyway is that a changeset can describe a change instead of spelling out SQL. A createTable or addColumn change is turned into SQL for the target database, and Liquibase knows how to reverse it. Raw SQL is supported too, with a rollback you write yourself.

Changelog formats
FormatLooks likeBest for
YAML- changeSet: ... changes: - createTable:Spring Boot's default; readable described changes
XML<changeSet><createTable> with an XSDEditor completion and validation from the schema
JSONThe same structure as YAMLChangelogs generated by tools
Formatted SQL--changeset author:id comments above plain SQLTeams that want to write SQL, with Liquibase's tracking and rollback comments

Spring Boot runs Liquibase's update at startup, before JPA. In Spring Boot 4, add spring-boot-starter-liquibase; in Spring Boot 3 you added org.liquibase:liquibase-core directly. The default master changelog is classpath:/db/changelog/db.changelog-master.yaml. The examples use Spring Boot 4.1, which brings Liquibase 5.0.4, against H2.

A first changelog

The master changelog creates a table in one changeset and adds a column in another, then includes a formatted SQL file that inserts two rows. Mixing formats like this is common: described changes for structure, SQL for data:

YAML
databaseChangeLog:
  - changeSet:
      id: 1-create-customer
      author: ann
      changes:
        - createTable:
            tableName: customer
            columns:
              - column:
                  name: id
                  type: int
                  constraints:
                    primaryKey: true
              - column:
                  name: name
                  type: varchar(50)
                  constraints:
                    nullable: false
  - changeSet:
      id: 2-add-email
      author: bob
      changes:
        - addColumn:
            tableName: customer
            columns:
              - column:
                  name: email
                  type: varchar(100)
  - include:
      file: data.sql
      relativeToChangelogFile: true
SQL
--liquibase formatted sql

--changeset ann:3-seed-customers
INSERT INTO customer (id, name, email) VALUES (1, 'Ann', 'ann@example.com');
INSERT INTO customer (id, name, email) VALUES (2, 'Bob', 'bob@example.com');
--rollback DELETE FROM customer WHERE id IN (1, 2);
Java
package liquibase.first;

import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;

@SpringBootApplication
public class FirstChangelog {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(FirstChangelog.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "spring.liquibase.change-log", "classpath:liquibase/basic/master.yaml"));
        try (var context = app.run(args)) {
            JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
            System.out.println("-- DATABASECHANGELOG");
            jdbc.query("SELECT ORDEREXECUTED, ID, AUTHOR, FILENAME, EXECTYPE"
                    + " FROM DATABASECHANGELOG ORDER BY ORDEREXECUTED",
                    (rs, row) -> String.format("%d | %-18s | %-4s | %-34s | %s",
                            rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4),
                            rs.getString(5)))
                    .forEach(System.out::println);
            System.out.println("-- DATABASECHANGELOGLOCK");
            System.out.println(jdbc.queryForMap("SELECT ID, LOCKED FROM DATABASECHANGELOGLOCK"));
            System.out.println("-- customer");
            jdbc.queryForList("SELECT name || ' ' || email FROM customer ORDER BY id",
                    String.class).forEach(System.out::println);
        }
    }
}
Output
-- DATABASECHANGELOG
1 | 1-create-customer  | ann  | liquibase/basic/master.yaml        | EXECUTED
2 | 2-add-email        | bob  | liquibase/basic/master.yaml        | EXECUTED
3 | 3-seed-customers   | ann  | liquibase/basic/data.sql           | EXECUTED
-- DATABASECHANGELOGLOCK
{ID=1, LOCKED=false}
-- customer
Ann ann@example.com
Bob bob@example.com
  • All three changesets ran in order, each recorded with its id, author and file. The SQL changeset's id and author came from its --changeset ann:3-seed-customers line, and its file is the included data.sql.
  • EXECTYPE is EXECUTED for all three. Other values appear later on this page: MARK_RAN for a changeset that was skipped but recorded.
  • The lock row is back to LOCKED=false after the update.
  • The table has both rows with their emails, so the addColumn ran before the insert that uses the column.

The file path is part of a changeset's identity. Moving or renaming a changelog file makes Liquibase see its changesets as new, and it tries to run them again; a createTable then fails because the table exists. Set logicalFilePath on a changelog if files may move.

Tags and rollback

Rollback is where Liquibase differs most from Flyway's free edition. This program tags the database after the first release, applies a second release with a new column and an index, previews the rollback SQL, rolls back to the tag, and finally tries to roll back a raw SQL change that has no rollback. It calls Liquibase's CommandScope API, the same commands the Liquibase CLI and build plugins run:

YAML
databaseChangeLog:
  - include:
      file: liquibase/basic/master.yaml
  - changeSet:
      id: 4-add-status
      author: cara
      changes:
        - addColumn:
            tableName: customer
            columns:
              - column:
                  name: status
                  type: varchar(10)
                  defaultValue: ACTIVE
  - include:
      file: index.sql
      relativeToChangelogFile: true
SQL
--liquibase formatted sql

--changeset cara:5-index-email
CREATE INDEX customer_email ON customer (email);
--rollback DROP INDEX customer_email;
YAML
databaseChangeLog:
  - include:
      file: liquibase/basic/master.yaml
  - changeSet:
      id: 4-uppercase-names
      author: dan
      changes:
        - sql:
            sql: UPDATE customer SET name = UPPER(name)
Java
package liquibase.rollback;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.util.Map;
import javax.sql.DataSource;
import liquibase.Scope;
import liquibase.command.CommandScope;
import liquibase.database.Database;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.resource.ClassLoaderResourceAccessor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;

@SpringBootApplication
public class Rollbacks {

    static String run(DataSource dataSource, String command, String... args)
            throws Exception {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try (Connection connection = dataSource.getConnection()) {
            Database database = DatabaseFactory.getInstance()
                    .findCorrectDatabaseImplementation(new JdbcConnection(connection));
            Scope.child(Scope.Attr.resourceAccessor.name(), new ClassLoaderResourceAccessor(),
                    () -> {
                CommandScope scope = new CommandScope(command)
                        .addArgumentValue("database", database);
                for (int i = 0; i < args.length; i += 2) {
                    scope.addArgumentValue(args[i], args[i + 1]);
                }
                scope.setOutput(output);
                scope.execute();
            });
        }
        return output.toString(StandardCharsets.UTF_8);
    }

    static void columns(JdbcTemplate jdbc) {
        System.out.println("  columns: " + jdbc.queryForList("SELECT COLUMN_NAME FROM"
                + " INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'CUSTOMER'"
                + " ORDER BY ORDINAL_POSITION", String.class)
                + ", changesets: " + jdbc.queryForList("SELECT ID FROM DATABASECHANGELOG"
                + " ORDER BY ORDEREXECUTED", String.class));
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(Rollbacks.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "spring.datasource.url", "jdbc:h2:mem:shop",
                "spring.liquibase.change-log", "classpath:liquibase/basic/master.yaml"));
        try (var context = app.run(args)) {
            DataSource dataSource = context.getBean(DataSource.class);
            JdbcTemplate jdbc = new JdbcTemplate(dataSource);
            System.out.println("After startup:");
            columns(jdbc);

            run(dataSource, "tag", "tag", "release-1");
            run(dataSource, "update", "changelogFile", "liquibase/release2/master.yaml");
            System.out.println("After tagging release-1 and updating to release 2:");
            columns(jdbc);

            System.out.println("rollbackSql to release-1 (preview only):");
            run(dataSource, "rollbackSql", "changelogFile", "liquibase/release2/master.yaml",
                    "tag", "release-1").lines()
                    .filter(line -> !line.isBlank() && !line.startsWith("-- *")
                            && !line.contains("DATABASECHANGELOGLOCK")
                            && !line.matches("-- (Ran at|Against|Lock|Release).*"))
                    .forEach(line -> System.out.println("  " + line));
            run(dataSource, "rollback", "changelogFile", "liquibase/release2/master.yaml",
                    "tag", "release-1");
            System.out.println("After rollback to release-1:");
            columns(jdbc);

            run(dataSource, "update", "changelogFile", "liquibase/norollback/master.yaml");
            System.out.println("Rolling back a raw SQL change without a rollback:");
            try {
                run(dataSource, "rollbackCount", "changelogFile",
                        "liquibase/norollback/master.yaml", "count", "1");
            } catch (Exception e) {
                Throwable cause = e;
                while (cause.getCause() != null) {
                    cause = cause.getCause();
                }
                System.out.println("  " + cause.getClass().getSimpleName() + ": "
                        + cause.getMessage());
            }
        }
    }
}
Output
After startup:
  columns: [ID, NAME, EMAIL], changesets: [1-create-customer, 2-add-email, 3-seed-customers]
Successfully tagged 'SA@jdbc:h2:mem:shop'
Running Changeset: liquibase/release2/master.yaml::4-add-status::cara
Running Changeset: liquibase/release2/index.sql::5-index-email::cara
Liquibase: Update has been successful. Rows affected: 0
After tagging release-1 and updating to release 2:
  columns: [ID, NAME, EMAIL, STATUS], changesets: [1-create-customer, 2-add-email, 3-seed-customers, 4-add-status, 5-index-email]
rollbackSql to release-1 (preview only):
  -- Rollback to 'release-1' Script
  -- Change Log: liquibase/release2/master.yaml
  -- Liquibase version: 5.0.4
  -- Rolling Back ChangeSet: liquibase/release2/index.sql::5-index-email::cara
  DROP INDEX customer_email;
  DELETE FROM PUBLIC.DATABASECHANGELOG WHERE ID = '5-index-email' AND AUTHOR = 'cara' AND FILENAME = 'liquibase/release2/index.sql';
  -- Rolling Back ChangeSet: liquibase/release2/master.yaml::4-add-status::cara
  ALTER TABLE PUBLIC.customer ALTER COLUMN  status SET DEFAULT NULL;
  ALTER TABLE PUBLIC.customer DROP COLUMN status;
  DELETE FROM PUBLIC.DATABASECHANGELOG WHERE ID = '4-add-status' AND AUTHOR = 'cara' AND FILENAME = 'liquibase/release2/master.yaml';
Rolling Back Changeset: liquibase/release2/index.sql::5-index-email::cara
Rolling Back Changeset: liquibase/release2/master.yaml::4-add-status::cara
After rollback to release-1:
  columns: [ID, NAME, EMAIL], changesets: [1-create-customer, 2-add-email, 3-seed-customers]
Running Changeset: liquibase/norollback/master.yaml::4-uppercase-names::dan
Liquibase: Update has been successful. Rows affected: 2
Rolling back a raw SQL change without a rollback:
Rolling Back Changeset: liquibase/norollback/master.yaml::4-uppercase-names::dan
ERROR: Exception Details
ERROR: Exception Primary Class:  RollbackImpossibleException
ERROR: Exception Primary Reason:  No inverse to liquibase.change.core.RawSQLChange created
ERROR: Exception Primary Source:  5.0.4
  RollbackImpossibleException: No inverse to liquibase.change.core.RawSQLChange created
  • The tag command marked the last applied changeset with release-1. The update to release 2 then skipped the three changesets that had already run ("Previously run: 3") and ran two new ones.
  • rollbackSql printed the rollback without running it. For the index it used the --rollback DROP INDEX line from the SQL file. For addColumn it generated the inverse itself, an ALTER TABLE ... DROP COLUMN, after first removing the column's default. Each step also deletes the changeset's row from DATABASECHANGELOG.
  • rollback to release-1 then ran those statements, newest first. The status column and the two history rows are gone.
  • The raw sql change that upper-cased the names has no automatic inverse. rollbackCount 1 failed with RollbackImpossibleException: No inverse to liquibase.change.core.RawSQLChange created. Add a rollback block to such changesets, or an empty one to say that rolling back means doing nothing.

The program trims the header comments, the lock statements, the time and the host name from the rollbackSql output, because they change on every run. Spring Boot can also write rollback SQL during startup with spring.liquibase.rollback-file and spring.liquibase.tag, which gives operators a ready script for each deployment.

Contexts and preconditions

Some changesets should run only in some environments, such as demo data in test databases. Others should run only if the database is in a certain state. Contexts handle the first case and preconditions the second:

YAML
databaseChangeLog:
  - changeSet:
      id: 1-create-product
      author: ann
      changes:
        - createTable:
            tableName: product
            columns:
              - column: {name: id, type: int, constraints: {primaryKey: true}}
              - column: {name: name, type: varchar(50)}
  - changeSet:
      id: 2-demo-products
      author: ann
      context: test
      changes:
        - insert:
            tableName: product
            columns:
              - column: {name: id, valueNumeric: 1}
              - column: {name: name, value: Demo desk}
  - changeSet:
      id: 3-copy-legacy-products
      author: bob
      preConditions:
        - onFail: MARK_RAN
        - tableExists:
            tableName: legacy_product
      changes:
        - sql:
            sql: INSERT INTO product SELECT id, name FROM legacy_product
Java
package liquibase.contexts;

import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;

@SpringBootApplication
public class ContextsAndPreconditions {

    static void start(String contexts) {
        SpringApplication app = new SpringApplication(ContextsAndPreconditions.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "spring.liquibase.change-log", "classpath:liquibase/contexts/master.yaml",
                "spring.liquibase.contexts", contexts));
        System.out.println("spring.liquibase.contexts=" + contexts);
        try (var context = app.run()) {
            JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
            jdbc.query("SELECT ID, EXECTYPE, CONTEXTS FROM DATABASECHANGELOG"
                    + " ORDER BY ORDEREXECUTED", (rs, row) -> String.format(
                            "  %-24s %-9s contexts=%s", rs.getString(1), rs.getString(2),
                            rs.getString(3)))
                    .forEach(System.out::println);
            System.out.println("  products: "
                    + jdbc.queryForList("SELECT name FROM product", String.class));
        }
    }

    public static void main(String[] args) {
        start("prod");
        start("test");
    }
}
Output
spring.liquibase.contexts=prod
  1-create-product         EXECUTED  contexts=null
  3-copy-legacy-products   MARK_RAN  contexts=null
  products: []
spring.liquibase.contexts=test
  1-create-product         EXECUTED  contexts=null
  2-demo-products          EXECUTED  contexts=test
  3-copy-legacy-products   MARK_RAN  contexts=null
  products: [Demo desk]
  • With spring.liquibase.contexts=prod, the changeset with context: test was left out completely: no row, no demo product. A changeset without a context runs in every context.
  • With contexts=test, on a fresh database, the demo product was inserted, and its history row records the context.
  • In both runs, the legacy_product table did not exist, so the precondition failed. onFail: MARK_RAN recorded the changeset as MARK_RAN without running it, so Liquibase will not try again. The default, HALT, would have stopped startup.

Contexts are chosen by the environment; labels (labels on a changeset, spring.liquibase.label-filter at runtime) are chosen by the changeset's author, for example to tag the changes of one feature. If spring.liquibase.contexts is not set, all changesets run, including the test ones, so set it explicitly in production.

Editing a changeset after it ran

Liquibase stores a checksum of each applied changeset and compares it on every start, like Flyway. This program writes a changelog to a temporary file, applies it, edits the column length, and starts again, then repeats the edit with validCheckSum:

Java
package liquibase.checksum;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ChecksumChange {

    static final String CHANGELOG = """
            databaseChangeLog:
              - changeSet:
                  id: 1-create-tag
                  author: ann
                  %s
                  changes:
                    - createTable:
                        tableName: tag
                        columns:
                          - column: {name: name, type: varchar(%d)}
            """;

    static void start(Path file, String label) {
        SpringApplication app = new SpringApplication(ChecksumChange.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "OFF",
                "spring.datasource.url", "jdbc:h2:mem:tags;DB_CLOSE_DELAY=-1",
                "spring.liquibase.change-log", file.toUri().toString()));
        try {
            app.run().close();
            System.out.println(label + ": started");
        } catch (RuntimeException e) {
            Throwable cause = e;
            while (cause.getCause() != null) {
                cause = cause.getCause();
            }
            System.out.println(label + ": " + cause.getClass().getSimpleName());
            cause.getMessage().lines().map(String::strip).filter(l -> !l.isEmpty())
                    .limit(3).map(l -> l.replace(file.toString(), "<changelog>"))
                    .forEach(l -> System.out.println("  " + l));
        }
    }

    public static void main(String[] args) throws Exception {
        Path file = Files.createTempFile("changelog", ".yaml");
        try {
            Files.writeString(file, CHANGELOG.formatted("", 20));
            start(file, "First start, varchar(20)");
            Files.writeString(file, CHANGELOG.formatted("", 40));
            start(file, "Changeset edited to varchar(40)");
            Files.writeString(file, CHANGELOG.formatted("validCheckSum: ANY", 40));
            start(file, "Same edit with validCheckSum: ANY");
        } finally {
            Files.delete(file);
        }
    }
}
Output
First start, varchar(20): started
Changeset edited to varchar(40): ValidationFailedException
  Validation Failed:
  1 changesets check sum
  file:<changelog>::1-create-tag::ann was: 9:4c9777810d803140d4b1aa40bfff5444 but is now: 9:40a9376e216022cca22153724019f1bf
Same edit with validCheckSum: ANY: started
  • After the edit, startup failed with ValidationFailedException: the stored checksum begins 9:4c97..., the new one 9:40a9.... The 9: prefix is the checksum algorithm version, which Liquibase raises when it changes how checksums are computed.
  • With validCheckSum: ANY on the changeset, the same edit was accepted and the application started. The changeset did not run again, because it was already recorded as applied, so the column in the database is still varchar(20).

That last point is the trap: validCheckSum and spring.liquibase.clear-checksums only silence the check. To change the schema, write a new changeset. For definitions that are meant to be replaced, such as views and procedures, mark the changeset runOnChange: true; it then runs again whenever its checksum changes, like a Flyway repeatable migration.

Configuration that matters

Common spring.liquibase properties
PropertyDefaultUse
spring.liquibase.change-logclasspath:/db/changelog/db.changelog-master.yamlThe master changelog
spring.liquibase.contexts, label-filterNone (everything runs)Choose changesets per environment or feature
spring.liquibase.enabledtrueTurn off migration at startup when a pipeline runs it
spring.liquibase.url, user, passwordThe application's DataSourceMigrate with a more privileged account
spring.liquibase.parameters.*NoneValues for ${name} placeholders in changelogs
spring.liquibase.rollback-file, tagNoneWrite rollback SQL for each update, and tag it
spring.liquibase.drop-firstfalseDrop the schema before updating; only for throwaway databases
spring.liquibase.analytics-enabledLiquibase's own defaultWhether Liquibase sends product usage data

If a migrating process is killed, the lock row can stay LOCKED=true, and every later start waits for it and then fails. Check that no migration is running, then clear it with the releaseLocks command or an UPDATE of DATABASECHANGELOGLOCK. With JPA, set spring.jpa.hibernate.ddl-auto=validate, as with Flyway.

Adopting Liquibase on a database that already has tables takes two commands. generateChangeLog writes a changelog that describes the current schema, and changelogSync records every changeset in it as applied without running anything. That is the counterpart of Flyway's baseline. From then on, new changesets are added to the end of the changelog as usual.

Liquibase or Flyway

Comparing the two migration tools
AspectLiquibaseFlyway
Unit of changeChangeset (id, author, file) in a changelogVersioned script, ordered by version number
FormatsYAML, XML, JSON, formatted SQLSQL and Java
OrderThe order in the changelogThe version numbers
RollbackGenerated for described changes, written for SQL, in the free editionUndo scripts in paid editions only
Several database types from one changelogYes, for described changesSeparate scripts per database
Environment filteringContexts and labelsSeparate locations
Learning curveHigher: changelog structure and change typesLower: numbered SQL files

Choose Flyway when the team writes SQL for one database type and wants the simplest model. Choose Liquibase when you need rollback scripts, one changelog for several database types, or environment-specific changes. Both are covered by Spring Boot in the same way; see the Flyway page for its version of these examples, the H2 page for the database used here, and Spring Data JPA for the entities that sit on top of the schema.