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 idauthor
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 createTableaddColumn
| Format | Looks like | Best for |
|---|---|---|
| YAML | - changeSet: ... changes: - createTable: | Spring Boot's default; readable described changes |
| XML | <changeSet><createTable> | Editor completion and validation from the schema |
| JSON | The same structure as YAML | Changelogs generated by tools |
| Formatted SQL | --changeset author:id | Teams 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-liquibaseorg.liquibase:liquibase-coreclasspath:/db/changelog/db.changelog-master.yaml
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:
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
--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);
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);
}
}
}
-- 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
line, and its file is the included--changeset ann:3-seed-customers .data.sql isEXECTYPE for all three. Other values appear later on this page:EXECUTED for a changeset that was skipped but recorded.MARK_RAN- The lock row is back to
after the update.LOCKED=false - The table has both rows with their emails, so the
ran before the insert that uses the column.addColumn
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 createTablelogicalFilePath
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
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
--liquibase formatted sql
--changeset cara:5-index-email
CREATE INDEX customer_email ON customer (email);
--rollback DROP INDEX customer_email;
databaseChangeLog:
- include:
file: liquibase/basic/master.yaml
- changeSet:
id: 4-uppercase-names
author: dan
changes:
- sql:
sql: UPDATE customer SET name = UPPER(name)
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());
}
}
}
}
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
command marked the last applied changeset withtag . The update to release 2 then skipped the three changesets that had already run ("Previously run: 3") and ran two new ones.release-1 printed the rollback without running it. For the index it used therollbackSql line from the SQL file. For--rollback DROP INDEX it generated the inverse itself, anaddColumn , after first removing the column's default. Each step also deletes the changeset's row fromALTER TABLE ... DROP COLUMN .DATABASECHANGELOG torollback then ran those statements, newest first. Therelease-1 column and the two history rows are gone.status- The raw
change that upper-cased the names has no automatic inverse.sql failed withrollbackCount 1 . Add aRollbackImpossibleException: No inverse to liquibase.change.core.RawSQLChange created block to such changesets, or an empty one to say that rolling back means doing nothing.rollback
The program trims the header comments, the lock statements, the time and the host name from the rollbackSqlspring.liquibase.rollback-filespring.liquibase.tag
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:
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
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");
}
}
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
, the changeset withspring.liquibase.contexts=prod was left out completely: no row, no demo product. A changeset without a context runs in every context.context: test - With
, on a fresh database, the demo product was inserted, and its history row records the context.contexts=test - In both runs, the
table did not exist, so the precondition failed.legacy_product recorded the changeset asonFail: MARK_RAN without running it, so Liquibase will not try again. The default,MARK_RAN , would have stopped startup.HALT
Contexts are chosen by the environment; labels (labelsspring.liquibase.label-filterspring.liquibase.contexts
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
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);
}
}
}
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
: the stored checksum beginsValidationFailedException , the new one9:4c97... . The9:40a9... prefix is the checksum algorithm version, which Liquibase raises when it changes how checksums are computed.9: - With
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 stillvalidCheckSum: ANY .varchar(20)
That last point is the trap: validCheckSumspring.liquibase.clear-checksumsrunOnChange: true
Configuration that matters
| Property | Default | Use |
|---|---|---|
spring.liquibase.change-log | classpath:/db/changelog/db.changelog-master.yaml | The master changelog |
spring.liquibase.contextslabel-filter | None (everything runs) | Choose changesets per environment or feature |
spring.liquibase.enabled | true | Turn off migration at startup when a pipeline runs it |
spring.liquibase.urluserpassword | The application's DataSource | Migrate with a more privileged account |
spring.liquibase.parameters.* | None | Values for ${name} |
spring.liquibase.rollback-filetag | None | Write rollback SQL for each update, and tag it |
spring.liquibase.drop-first | false | Drop the schema before updating; only for throwaway databases |
spring.liquibase.analytics-enabled | Liquibase's own default | Whether Liquibase sends product usage data |
If a migrating process is killed, the lock row can stay LOCKED=truereleaseLocksUPDATEDATABASECHANGELOGLOCKspring.jpa.hibernate.ddl-auto=validate
Adopting Liquibase on a database that already has tables takes two commands. generateChangeLogchangelogSync
Liquibase or Flyway
| Aspect | Liquibase | Flyway |
|---|---|---|
| Unit of change | Changeset (id, author, file) in a changelog | Versioned script, ordered by version number |
| Formats | YAML, XML, JSON, formatted SQL | SQL and Java |
| Order | The order in the changelog | The version numbers |
| Rollback | Generated for described changes, written for SQL, in the free edition | Undo scripts in paid editions only |
| Several database types from one changelog | Yes, for described changes | Separate scripts per database |
| Environment filtering | Contexts and labels | Separate locations |
| Learning curve | Higher: changelog structure and change types | Lower: 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