Spring Boot Flyway
Flyway
Flyway is database migration tool. I already explained about it, and please check the last entry Database Migration with Flyway
Flyway and Spring Boot
When starting Spring Boot App, Flyway checks current database status and Flyway migrate database automatically. It’s so useful.
And setup is very easy. While developing app, we can create and drop database so easy.
Dependencies
Let’s use Flyway with MySQL.
The dependencies are following
build.gradle
dependencies { compile("org.springframework.boot:spring-boot-starter-web") compile('org.springframework.boot:spring-boot-starter-data-jpa') compile('org.flywaydb:flyway-core') compile("mysql:mysql-connector-java:5.1.40") testCompile("org.springframework.boot:spring-boot-starter-test") }
starter-data-jpa, flyway-core, mysql-connector are required.
Other gradle file is not special
Applicaiton configuration file(application.yml)
application.yml
spring: datasource: url: jdbc:mysql://localhost:3306/flywaysample username: root password: driver-class-name: com.mysql.jdbc.Driver
This is datasource setting.
Setup for MySQL. Database name is flywaysample
Create database
Please create blank database.
If you missed creating database, error has happened when you start application
Migration file
By default migration file location is src/main/resources/db/migration
The name has rule
V
Ex) V1__create-table.sql
Don’t forget 2 underscore after version number.
If you want to add new migration please add next version number.
V1_
This is an example
CREATE TABLE IF NOT EXISTS `admin` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '', `email` VARCHAR(255) NOT NULL COMMENT '', `password` TEXT NOT NULL COMMENT '', `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '', `updated` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '', PRIMARY KEY (`id`) COMMENT '', UNIQUE INDEX `email_UNIQUE` (`email` ASC) COMMENT '') ENGINE = InnoDB;
This is generated by mysql workbench. I copy schema and paste v1 file.
Start app and migration
You are ready to start application.
Start Spring boot app. Flyway will do migration.
Flyway manages database status by schema_version table.
This table is created by default when starting app.
Source code? No need!