In this blog I’m going to talk about integrating Flyway in your Spring Boot application. It is a migrating library that automates and keeps track of database changes, it’s basically version control for your database.
How Flyway works
In order to use Flyway you need to add the dependency to your pom.xml or build.gradle file. For maven use the following dependency.
<dependency> <groupId>org.flywaydb</groupId> <artifactId>flyway-core</artifactId> <version>7.0.1</version> </dependency>
For Gradle use the following dependency.
compile group: 'org.flywaydb', name: 'flyway-core', version: '7.0.1'
You then need to create a directory called db and another directory called migration which is the default location for migration script files. Create sql files with names following the format of a capital V followed by the version number followed by two underscores followed by the file name.
Finally you need to add the following lines to your application.properties file. Make sure not to modify you sql files. If you need to modify them add a new version or if you really want to modify the files drop the database and recreate it.
spring.jpa.hibernate.ddl-auto = validate spring.datasource.validationQuery= SELECT 1 spring.flyway.baseline-on-migrate=true spring.flyway.locations=classpath:db/migration
By leveraging a database migration library such as Flyway, you can effectively streamline the software upgrade process and get rid of manual database upgrade steps from the implementation.
You also won’t need to precede each creates a table statement with a drop table statement to ensure that the database structure is recreated each time you start your application as this is not optimal.