Chapter 4: Migration with Liquibase
Introduction
Liquibase is a popular alternative to Flyway. While Flyway mainly uses raw SQL, Liquibase offers a database-agnostic format (XML, YAML, JSON) that can be converted into SQL for different DBs.
🎯 Chapter Objectives
By the end of this chapter, you will know how to:
- ✅ Understand the differences between Flyway and Liquibase
- ✅ Configure Liquibase with Spring Boot
- ✅ Create changelogs in XML, YAML, and SQL
- ✅ Use automatic rollbacks
- ✅ Choose between Flyway and Liquibase
1. Flyway vs Liquibase
Quick Comparison
| Aspect | Flyway | Liquibase |
|---|---|---|
| Main format | Native SQL | XML, YAML, JSON, SQL |
| Learning curve | Very easy | Medium |
| Multi-DB portability | Low (specific SQL) | High |
| Rollback | Manual | Automatic for some operations |
| Community | Very large | Large |
| Spring Boot | Excellent integration | Excellent integration |
When to Choose Flyway?
✅ Use Flyway if:
- You use a single database
- You prefer native SQL
- You want maximum simplicity
- Your team is well-versed in SQL
When to Choose Liquibase?
✅ Use Liquibase if:
- You need to support multiple DBs (PostgreSQL, MySQL, Oracle...)
- You want automatic rollbacks
- You prefer declarative formats (YAML, XML)
- You have complex changes to manage
2. Installation
Maven Dependency
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</dependency>
caution
Warning: Do not use Flyway and Liquibase together in the same project!
3. File Structure
Recommended Structure
src/
└── main/
└── resources/
└── db/
└── changelog/
├── db.changelog-master.xml # Main file
├── changes/
│ ├── 001-create-users.xml
│ ├── 002-add-email.xml
│ └── 003-create-orders.xml
└── data/
└── initial-data.xml # Initial data
Master File (Entry Point)
<!-- db.changelog-master.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd">
<!-- Include change files -->
<include file="db/changelog/changes/001-create-users.xml"/>
<include file="db/changelog/changes/002-add-email.xml"/>
<include file="db/changelog/changes/003-create-orders.xml"/>
<!-- Or include an entire folder -->
<includeAll path="db/changelog/data/"/>
</databaseChangeLog>
4. XML Format
Create a Table
<!-- 001-create-users.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd">
<changeSet id="1" author="dev">
<comment>Create the users table</comment>
<createTable tableName="users">
<column name="id" type="BIGINT" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="username" type="VARCHAR(50)">
<constraints nullable="false" unique="true"/>
</column>
<column name="password" type="VARCHAR(100)">
<constraints nullable="false"/>
</column>
<column name="created_at" type="TIMESTAMP" defaultValueComputed="CURRENT_TIMESTAMP"/>
</createTable>
<!-- Automatic rollback: DROP TABLE users -->
</changeSet>
</databaseChangeLog>
Add a Column
<!-- 002-add-email.xml -->
<databaseChangeLog ...>
<changeSet id="2" author="dev">
<comment>Add the email column</comment>
<addColumn tableName="users">
<column name="email" type="VARCHAR(100)">
<constraints unique="true"/>
</column>
</addColumn>
<!-- Automatic rollback: DROP COLUMN email -->
</changeSet>
</databaseChangeLog>
Create an Index
<changeSet id="3" author="dev">
<createIndex tableName="users" indexName="idx_users_email">
<column name="email"/>
</createIndex>
</changeSet>
Insert Data
<changeSet id="4" author="dev">
<insert tableName="users">
<column name="username" value="admin"/>
<column name="password" value="$2a$10$hashedpassword"/>
<column name="email" value="admin@example.com"/>
</insert>
<!-- Manual rollback required -->
<rollback>
DELETE FROM users WHERE username = 'admin';
</rollback>
</changeSet>
5. YAML Format
Much more readable than XML!
Create a Table
# 001-create-users.yaml
databaseChangeLog:
- changeSet:
id: 1
author: dev
comment: Create the users table
changes:
- createTable:
tableName: users
columns:
- column:
name: id
type: BIGINT
autoIncrement: true
constraints:
primaryKey: true
nullable: false
- column:
name: username
type: VARCHAR(50)
constraints:
nullable: false
unique: true
- column:
name: password
type: VARCHAR(100)
constraints:
nullable: false
- column:
name: created_at
type: TIMESTAMP
defaultValueComputed: CURRENT_TIMESTAMP
Add a Column
# 002-add-email.yaml
databaseChangeLog:
- changeSet:
id: 2
author: dev
comment: Add email to users
changes:
- addColumn:
tableName: users
columns:
- column:
name: email
type: VARCHAR(100)
constraints:
unique: true
Master File in YAML
# db.changelog-master.yaml
databaseChangeLog:
- include:
file: db/changelog/changes/001-create-users.yaml
- include:
file: db/changelog/changes/002-add-email.yaml
- includeAll:
path: db/changelog/data/
6. SQL Format (Like Flyway)
You can also use raw SQL:
-- 001-create-users.sql
-- liquibase formatted sql
-- changeset dev:1
-- comment: Create the users table
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- rollback DROP TABLE users;
-- 002-add-email.sql
-- liquibase formatted sql
-- changeset dev:2
ALTER TABLE users ADD COLUMN email VARCHAR(100) UNIQUE;
-- rollback ALTER TABLE users DROP COLUMN email;
7. Spring Boot Configuration
Minimal Configuration
# application.properties
spring.liquibase.enabled=true
spring.liquibase.change-log=classpath:db/changelog/db.changelog-master.xml
Full Configuration
# Enable Liquibase
spring.liquibase.enabled=true
# Main changelog file
spring.liquibase.change-log=classpath:db/changelog/db.changelog-master.yaml
# Schemas
spring.liquibase.default-schema=public
spring.liquibase.liquibase-schema=public
# Contexts (dev, test, prod)
spring.liquibase.contexts=dev
# Labels
spring.liquibase.labels=
# Rollback on failure
spring.liquibase.rollback-file=rollback.sql
YAML Format
spring:
liquibase:
enabled: true
change-log: classpath:db/changelog/db.changelog-master.yaml
default-schema: public
contexts: dev
8. Rollbacks
Automatic Rollback
Liquibase automatically generates rollbacks for:
| Operation | Automatic Rollback |
|---|---|
| createTable | DROP TABLE |
| addColumn | DROP COLUMN |
| createIndex | DROP INDEX |
| addForeignKey | DROP FOREIGN KEY |
| insert | ❌ (manual) |
| update | ❌ (manual) |
| delete | ❌ (manual) |
| sql | ❌ (manual) |
Manual Rollback
<changeSet id="5" author="dev">
<update tableName="users">
<column name="status" value="ACTIVE"/>
<where>status IS NULL</where>
</update>
<!-- Manual rollback required -->
<rollback>
<update tableName="users">
<column name="status" valueComputed="NULL"/>
<where>status = 'ACTIVE'</where>
</update>
</rollback>
</changeSet>
Execute a Rollback
# Rollback the last changeset
mvn liquibase:rollback -Dliquibase.rollbackCount=1
# Rollback to a tag
mvn liquibase:rollback -Dliquibase.rollbackTag=v1.0
# Rollback to a date
mvn liquibase:rollback -Dliquibase.rollbackDate=2025-01-01
9. Contexts and Labels
Contexts
Run certain changesets only in certain environments:
<!-- Only in dev -->
<changeSet id="10" author="dev" context="dev">
<insert tableName="users">
<column name="username" value="testuser"/>
</insert>
</changeSet>
<!-- Only in prod -->
<changeSet id="11" author="dev" context="prod">
<insert tableName="config">
<column name="key" value="feature.flag"/>
<column name="value" value="true"/>
</insert>
</changeSet>
# application-dev.properties
spring.liquibase.contexts=dev
# application-prod.properties
spring.liquibase.contexts=prod
Labels
Group changesets by feature:
<changeSet id="20" author="dev" labels="user-feature">
<!-- User-related changes -->
</changeSet>
<changeSet id="21" author="dev" labels="order-feature">
<!-- Order-related changes -->
</changeSet>
10. The DATABASECHANGELOG Table
Liquibase tracks changes in a table:
SELECT * FROM DATABASECHANGELOG;
| ID | AUTHOR | FILENAME | DATEEXECUTED | ORDEREXECUTED | EXECTYPE | MD5SUM | DESCRIPTION |
|---|---|---|---|---|---|---|---|
| 1 | dev | 001-create-users.xml | 2025-01-15 | 1 | EXECUTED | abc123 | createTable tableName=users |
| 2 | dev | 002-add-email.xml | 2025-01-15 | 2 | EXECUTED | def456 | addColumn tableName=users |
11. Maven Commands
<plugin>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-maven-plugin</artifactId>
<configuration>
<propertyFile>src/main/resources/liquibase.properties</propertyFile>
</configuration>
</plugin>
# Check status
mvn liquibase:status
# Apply changes
mvn liquibase:update
# Generate SQL without executing
mvn liquibase:updateSQL
# Rollback
mvn liquibase:rollback -Dliquibase.rollbackCount=1
# Create a tag
mvn liquibase:tag -Dliquibase.tag=v1.0
# Generate a changelog from an existing DB
mvn liquibase:generateChangeLog
12. Summary
Key Points
| Concept | Description |
|---|---|
| ChangeLog | Main file listing changes |
| ChangeSet | An atomic change (unique id + author) |
| Contexts | Filter changesets by environment |
| Labels | Group changesets by feature |
| Rollback | Undo changes (auto or manual) |
When to Use Which Tool?
Minimal Configuration
# application.yml with Liquibase
spring:
liquibase:
enabled: true
change-log: classpath:db/changelog/db.changelog-master.yaml
Minimal Master File
# db.changelog-master.yaml
databaseChangeLog:
- includeAll:
path: db/changelog/changes/
🎯 Next Step
You now have all the theory! It's time to practice with the practical exercises.
➡️ TP7.1: Datasource and Pool Configuration