In this tutorial, you will learn using Flyway to version control database migration/evolution. Let's start building an example with Spring Boot, JPA/Hibernate, MySQL, and Docker.

What you will need

  • JDK 8+ or OpenJDK 8+
  • Maven 3+
  • MySQL Server 5+ or Docker CE 18+

Init project structure and dependencies

Project structure

├── src
│   └── main
│       ├── java
│       │   └── com
│       │       └── hellokoding
│       │           └── springboot
│       │               └── jpa
│       │                   ├── book
│       │                   │   ├── Book.java
│       │                   │   └── BookRepository.java
│       │                   └── Application.java
│       └── resources
│           ├── db
│           │   └── migration
│           │       ├── V1.0__init.sql
│           │       └── V1.1__insert_data.sql
│           └── application.properties
├── Dockerfile
├── docker-compose.yml
└── pom.xml

Project dependencies


Define JPA Entity, Repository and Prepare SQL Script

Define JPA Entity and Repository



Prepare SQL script for database migration



Config and Run

Application Configurations


hk-mysql refers to Docker Compose service defined in the below docker-compose.yml file


Run with Docker

Prepare Dockerfile for Java/Spring Boot application and docker-compose.yml for MySQL Server



Type the below command at the project root directory, make sure your local Docker is running

docker-compose up  

Access to MySQL Server docker container by issuing below bash command and key in hellokoding on Enter password:

docker exec -it hk-mysql mysql -p

Run with JDK/OpenJDK, Maven and MySQL Server local

Update hk-mysql on application.properties to localhost and type the below command at the project root directory

mvn clean spring-boot:run  

Testing time

Check the created schema and data by Flyway based on the prepared SQL scripts

Flyway also produced an additional table flyway_schema_history to manage schema version history

Keys to take away

  • Using Flyway to version control database migration/evolution with SQL scripts.
  • Hibernate DDL Auto should be disable when using with Flyway or on production environment, on application.properties, spring.jpa.hibernate.ddl-auto value should be validate or none (default).
  • By default, Spring Boot and Flyway will find the migration script in resources/db/migration, you can change it on application.properties with spring.flyway.locations property.
  • SQL script file name should follow Flyway convention https://flywaydb.org/documentation/migrations#naming

Source code

https://github.com/hellokoding/hellokoding-courses/tree/master/springboot-examples/springboot-flyway