In this tutorial we will look into using Spring Boot Flyway with PostgreSQL database. We will be using gradle as the build tool.
What is Flyway ?
It is required for database migration. Suppose you need some db scripts to be run before your application is up and running, then you can use this.
The other alternative to Flyway is Liquibase.
Lets create a spring boot project from spring initializr by adding below dependencies:
* Spring boot starter web
* JPA
* Flyway
* PostgreSQL
* Lombok
The entire build.gradle would look something like below:
plugins { id 'java' id 'org.springframework.boot' version '2.7.12' id 'io.spring.dependency-management' version '1.0.15.RELEASE' } group = 'com.heapsteep' version = '0.0.1-SNAPSHOT' sourceCompatibility = '14' configurations { compileOnly { extendsFrom annotationProcessor } } repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.flywaydb:flyway-core' compileOnly 'org.projectlombok:lombok' runtimeOnly 'org.postgresql:postgresql' annotationProcessor 'org.projectlombok:lombok' testImplementation 'org.springframework.boot:spring-boot-starter-test' } tasks.named('test') { useJUnitPlatform() }
Write a entity class. In our example we will name it as Person.java:
@Data @Entity @Table(name = "PERSONS") public class Person { @Id @GeneratedValue private int id; private String first_name; private String last_name; private String mobile; }
Have the db configurations in application.properties file:
spring.datasource.url = jdbc:postgresql://192.168.99.100:5432/demo_db spring.datasource.username = postgres spring.datasource.password = root spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect spring.flyway.baseline-on-migrate=true
Add all the db scripts file in the form of .sql file and keep it inside this package: /resources/db/migration/ .While naming the scripts file you have to follow a naming convention, the file name should start with the Version number followed by 2 underscores then you can give any text. For e.g., V1__*.sql, V2__*.sql.
So first V1__ file will be executed and followed by V2__, and so forth and so on…
What are the DB scripts executed, that trail you can find it in this table: flyway_schema_history
Run this gradle task for the project: “bootrun“.
After the successful run it will create respective tables in the PostgreSQL DB along with the data being populated.
Thats all !…
The GitHub source code for the above application is here: https://github.com/heapsteep/flyway-gradle