introduction :
This tutorial will guide you through setting up a Spring Boot application and integrating Liquibase for database version control.
Prerequisites:
- Basic understanding of Java and Spring Boot.
- An Integrated Development Environment (IDE) like IntelliJ or Eclipse installed.
- A database (e.g., PostgreSQL, MySQL) installed and running.
- Maven or Gradle installed for dependency management.
Step 1: Create a Spring Boot Project
Use Spring Initializer to create a new Spring Boot project with the following dependencies:
- Spring Web
- Spring Data JPA
- H2 Database (or the database of your choice)
Step 2: Configure Database in application.properties
Open src/main/resources/application.properties
(or application.yml
) and configure your database connection details. For example, with H2:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
Step 3: Add Liquibase Dependency
Add the Liquibase dependency to your pom.xml
(if using Maven) or build.gradle
(if using Gradle):
For Maven:
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</dependency>
For Gradle:
implementation 'org.liquibase:liquibase-core'
Step 4: Create Liquibase Change Log File
Create a new folder in src/main/resources
named db/changelog
and add a new Liquibase change log file, for example, changelog.xml
. In this file, you will define your database changes using Liquibase syntax.
<?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-4.0.xsd">
<changeSet id="1" author="your_name">
<!-- Add your database changes here -->
<createTable tableName="example_table">
<column name="id" type="BIGINT" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="name" type="VARCHAR(255)"/>
</createTable>
</changeSet>
</databaseChangeLog>
Step 5: Configure Liquibase in application.properties
Update your application.properties
file to tell Spring Boot where to find the Liquibase change log:
spring.liquibase.change-log=classpath:db/changelog/changelog.xml
Step 6: Run the Spring Boot Application
Run your Spring Boot application. Liquibase will automatically apply the database changes specified in your change log file.
Step 7: Verify the Database Changes
Check your database to ensure that the changes have been applied. You should see a new table named example_table
with columns id
and name
.