Spring Boot + Flyway Migration
What is Flyway?
Flyway is an open source database migration software. It has Migrate, Clean, Info, Validate, Undo, Baseline, and Repair seven basic commands, SQL (database-specific syntax (such as PL/SQL, T-SQL, etc.) or Java migrations are supported (for advanced data transformations or dealing with LOBs).
Spring Boot integrates with Flyway, one of the most extensively used database migration tools, to make database migrations easier.
Flyway is a tool that allows you to version control incremental changes to your database such that you can easily and completely migrate to a new version.
In this tutorial, we will learn how to utilise Flyway to handle database changes in Spring Boot/Java applications, i.e using Flyway Java base migration.
We'll create a new Spring Boot project with a MySQL database and Spring Data JPA, as well as learn how to incorporate Flyway into it.
Refer example for Flyway Command Line base migration.
Now, let's create Spring Boot application from Spring Initializr.
Project Structure
Maven Dependency
Add flyway-core
for flyway dependency, mysql-connector-java
for mysql
database.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.techgeeknext</groupId>
<artifactId>flyway-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-flyway-example</name>
<description>Spring Boot Flyway</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Configuring MySQL
Provide Mysql database connection details in application.properties
file.
spring.datasource.url=jdbc:mysql://localhost/techgeeknextFlywaydb?createDatabaseIfNotExist=true&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.platform=mysql
spring.jpa.hibernate.ddl-auto=update
Take a look at our suggested posts:
Entity
Create Employee entity, so that we can our flyway database migration example.
package com.techgeeknext.entity;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import lombok.Data;
@Entity
@Table(name = "employees")
@Data
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Column(unique = true)
@Size(min = 1, max = 100)
private String name;
@NotBlank
@Size(max = 50)
private String role;
@Size(max = 50)
private String project;
}
JPA Repository
Create Employee repository class.
package com.techgeeknext.repository;
import com.techgeeknext.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
Flyway Migration script
By default, Flyway attempts to read database migration scripts from the db/migration
folder.
- V[VERSION_NUMBER__[NAME].sql
is a naming standard that must be followed by all
migration scripts.
To understand more about the naming convention, refer the
Official Flyway Documentation.
Create Employee Table Schema
Now, inside the src/main/resources/db/migration
directory, create a new file named
V1__init.sql
and add the following sql scripts:
CREATE TABLE employees (
id bigint(20) NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL,
role varchar(50) NOT NULL,
project varchar(50) DEFAULT NULL,
PRIMARY KEY (id),
UNIQUE KEY UK_name (name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Test Flyway Migration
Run the Spring Boot application using mvn spring-boot:run
.
When the application starts, you'll notice two tables created in Mysql database: one for employees
and another for the fly database named flyway_schema_history
.
In the table, it keeps track of the current migration's version, script file name, and checksum, among other things.
If you make changes to V1__init.sql
after the migration is complete, Flyway will
complain that the
checksums don't match.
As a result, any modifications to the schema must be made in a new migration script file with a new
version V2__[NAME].sql
, which Flyway will apply when you start the application.
Test adding more migration script
Create a new version2 migration script V2__employeedata.sql
under same package db/migration
to watch how Flyway
automatically migrates the database to the new version.
INSERT INTO employees(name, role, project) VALUES('techgeeknext-user1', 'Developer', 'Flyway-Project1');
INSERT INTO employees(name, role, project) VALUES('techgeeknext-user2', 'SME', 'Flyway-Project2');
Liquibase is another popular Flyway alternative.
Differences between Flyway and Liquibase
Refer Differences between Flyway and Liquibase to understand more.Download Source Code
The full source code for this article can be found on below.Download it here - Spring Boot + Flyway Migration Example
You learnt how to use Flyway to version database changes in a Spring Boot application in this post.