1. What is Liquibase?
Liquibase is a database version control tool. It allows you to manage schema changes (like creating tables, adding columns, indexes, etc.) across environments in a consistent way. With Spring Boot, it integrates seamlessly.
2. Add Dependencies
In your pom.xml
(Maven project):
<dependencies>
<!-- Spring Boot Starter Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- H2 database (or use MySQL/Postgres/etc.) -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Liquibase -->
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</dependency>
</dependencies>
For Gradle:
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'com.h2database:h2'
implementation 'org.liquibase:liquibase-core'
3. Configure Liquibase in application.yml
(or .properties
)
spring:
datasource:
url: jdbc:h2:mem:testdb
username: sa
password: password
driver-class-name: org.h2.Driver
liquibase:
change-log: classpath:db/changelog/db.changelog-master.yaml
Here, we tell Spring Boot where the Liquibase changelog file is.
4. Create Liquibase Changelog File
Create folder: src/main/resources/db/changelog/
Inside it, create: db.changelog-master.yaml
databaseChangeLog:
- changeSet:
id: 1
author: demo
changes:
- createTable:
tableName: customer
columns:
- column:
name: id
type: BIGINT
autoIncrement: true
constraints:
primaryKey: true
- column:
name: name
type: VARCHAR(255)
constraints:
nullable: false
- column:
name: email
type: VARCHAR(255)
constraints:
unique: true
5. Run the Application
When you start your Spring Boot app:
- Liquibase will automatically run the changelog.
- The table
customer
will be created in the database. - Liquibase will also create internal tables (
DATABASECHANGELOG
,DATABASECHANGELOGLOCK
) to track executed changes.
6. Example JPA Entity
You can map the created table:
import jakarta.persistence.*;
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Column(unique = true, nullable = false)
private String email;
// getters and setters
}
7. Adding Another Change
Later, if you want to add a new column:
- changeSet:
id: 2
author: demo
changes:
- addColumn:
tableName: customer
columns:
- column:
name: phone
type: VARCHAR(20)
Restart your app → Liquibase sees that changeSet 2
hasn’t run yet, and applies it.