DEV Community

Sachin Sarawgi
Sachin Sarawgi

Posted on • Originally published at Medium

Getting started with Spring Boot and Liquibase

Java developers often use the Spring Boot framework to create web apps. It has a number of features that make it simple to start using and develop reliable, scalable apps. An open-source tool for managing database schema is called Liquibase. It makes it simple for developers to handle database changes, migrate between schema versions, and version control the database schema. Using a straightforward example, we’ll go over how to get started with Spring Boot and Liquibase in this tutorial.

Step 1: Create a new Spring Boot project

To create a new Spring Boot project, you can use the Spring Initializr. This web-based tool allows you to generate a new Spring Boot project with all the necessary dependencies and configurations.

  1. Open your web browser and navigate to the Spring Initializr website at https://start.spring.io/.
  2. Fill in the following details: – Project: Maven Project – Language: Java – Spring Boot: 3.0.5 – Group: com.springboot – Artifact: learningLiquibase – Packaging: Jar – Java: 11 – Description: Getting started with Spring Boot & Liquibase
  3. Click on Add dependencies and add the following dependencies: – Spring Web – Spring Data JPA – H2 Database – Liquibase Migration
  4. Click on Generate and download the generated zip file.
  5. After all configuration, the setup should look like this.

Step 2: Setup the database

In this example, we’ll use the H2 database. Spring Boot comes with auto-configuration for H2, so we don’t need additional configuration.

  • Open the application.properties file located in the src/main/resources directory and add the following properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=learner
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialectydsfjbm
Enter fullscreen mode Exit fullscreen mode

These properties configure the H2 database for our application.

  • Create a new file called schema.sql in the src/main/resources directory and add the following SQL statements:
CREATE TABLE customer (
  id INT PRIMARY KEY,
  name VARCHAR(50)
);
Enter fullscreen mode Exit fullscreen mode

This will create a table called customer with two columns: id and name.

Step 3: Configure Liquibase

Liquibase provides a way to version control the database schema and manages database changes. In this step, we’ll configure Liquibase for our Spring Boot application.

  • Create a new file called liquibase.properties in the src/main/resources directory and add the following properties:
spring.liquibase.change-log=classpath:/db/changelog/db.changelog-master.yaml
Enter fullscreen mode Exit fullscreen mode

This property tells Liquibase where to find the changelog file.

  • Create a following directory path db/changelog in the src/main/resources directory.
  • Create a new file called db.changelog-master.yaml in the src/main/resources/db/changelog directory and add the following content:
databaseChangeLog:
  - include:
      file: classpath:/db/changelog/changes/001-initial-schema.sql
Enter fullscreen mode Exit fullscreen mode

This file defines a master changelog that includes a single changelog file called 001-initial-schema.sql.

  • Create a new directory called changes in the src/main/resources/db/changelog directory.
  • Create a new file called 001-initial-schema.sql in the src/main/resources/db/changelog/changes directory and add the following SQL statements:
CREATE TABLE customer (
  id INT PRIMARY KEY,
  name VARCHAR
Enter fullscreen mode Exit fullscreen mode

This file contains the same SQL statements that we added to schema.sql. This is because we want Liquibase to create the same database schema that we defined in schema.sql.

Step 4: Create a REST Controller

  • Create a new file called CustomerController.java in the src/main/java/com/springboot/learningLiquibase directory and add the following content:
   package com.springboot.learningLiquibase;

   import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.http.HttpStatus;
   import org.springframework.http.ResponseEntity;
   import org.springframework.web.bind.annotation.GetMapping;
   import org.springframework.web.bind.annotation.RestController;

   import java.util.List;

   @RestController
   public class CustomerController {

       @Autowired
       private CustomerRepository customerRepository;

       @GetMapping("/customers")
       public ResponseEntity<List<Customer>> getAllCustomers() {
           List<Customer> customers = customerRepository.findAll();
           return new ResponseEntity<>(customers, HttpStatus.OK);
       }
   }
Enter fullscreen mode Exit fullscreen mode

This class defines a REST controller with a single endpoint that returns a list of customers. It uses the CustomerRepository to retrieve the data from the database.

  • Create a new file called CustomerRepository.java in the src/main/java/com/springboot/learningLiquibase directory and add the following content:
package com.springboot.learningLiquibase;

import org.springframework.data.jpa.repository.JpaRepository;

public interface CustomerRepository extends JpaRepository<Customer, Integer> {
}
Enter fullscreen mode Exit fullscreen mode

This interface extends the JpaRepository interface and defines a repository for the Customer entity. It provides methods for common database operations such as findAll(), findById(), save(), and delete().

  • Create a new file called Customer.java in the src/main/java/com/springboot/learningLiquibasedirectory and add the following content:
package com.springboot.learningLiquibase;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Customer {

    @Id
    private Integer id;

    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
Enter fullscreen mode Exit fullscreen mode

This class defines the Customer entity with two properties: id and name. It uses JPA annotations to map the entity to the customer table in the database.

Step 5: Run the application

  • Open a terminal window and navigate to the root directory of the project.
  • Build the application by running the following command
java -jar target/liquibase-demo-0.0.1-SNAPSHOT.jar
Enter fullscreen mode Exit fullscreen mode

This will start the application and listen for incoming HTTP requests.

Step 6: Test the application

  • Open a web browser and navigate to http://localhost:8080/customers.
  • You should see a JSON response containing an empty array []. This is because we still need to add customers to the database.
  • Open a command prompt and navigate to the root directory of the project.
  • Run the following command to start the H2 console:
java -jar target/liquibase-demo-0.0.1-SNAPSHOT.jar --spring.h2.console.enabled=true
Enter fullscreen mode Exit fullscreen mode

This will start the H2 console and open a web browser window.

  • In the H2 console, enter the following JDBC URL:
jdbc:h2:mem:testdb
Enter fullscreen mode Exit fullscreen mode

This will connect to the in-memory H2 database.

  • Click on the Connect button.
  • You should see the CUSTOMER table in the list of tables. Click on the table
  • Click on the SQL tab and enter the following SQL statement to insert a new customer:
INSERT INTO CUSTOMER (ID, NAME) VALUES (1, 'John Doe');
Enter fullscreen mode Exit fullscreen mode

This will insert a new row into the CUSTOMER table with id 1 and name "John Doe".

  • Click on the Run button to execute the SQL statement.
  • Refresh the web browser window and you should see a JSON response containing a single customer with id 1 and name "John Doe".

Congratulations! You have successfully created a Spring Boot application with Liquibase integration and tested it by adding a new customer to the database and retrieving the data through a REST API.

Step 7: Additional configuration

  • By default, Liquibase will look for a changelog file named db.changelog-master.yaml in the resources/db/changelog directory. You can change the location of the file by setting the spring.liquibase.change-log property in the application.properties file.
  • For example, to use a changelog file named liquibase-changelog.yaml in the root directory of the project, add the following line to the application.properties file:
spring.liquibase.change-log=classpath:/liquibase-changelog.yaml
Enter fullscreen mode Exit fullscreen mode
  • You can also configure Liquibase to use a different database than H2. To do this, you need to add the appropriate JDBC driver dependency to the pom.xml file and set the spring.datasource.url, spring.datasource.username, and spring.datasource.password properties in the application.properties file. For example, to use MySQL as the database, add the following dependency to the pom.xml file:
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.23</version>
</dependency>
Enter fullscreen mode Exit fullscreen mode

Then, set the following properties in the application.properties file:

spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
Enter fullscreen mode Exit fullscreen mode
  • Replace mydb, root, and password with your own database name, username, and password, respectively.

That’s it! You now have a fully functional Spring Boot application with Liquibase integration. You can use this project as a starting point for your own applications and customize them as needed.

If you like the content, make sure to live a like :).

Top comments (0)