How to Use Flyway Database Migration Tool with JDBC?
Last Updated :
26 Feb, 2024
Flyway is a powerful database migration tool. It simplifies and automates the process of managing database schema changes. Flyway follows the simple principle of versioning the database schema using SQL scripts. These scripts are organized in a specific folder structure and executed in a sequential order.
In this article, we will learn how to use Flyway with JDBC for effective database migration.
Prerequisites:
- Download and install Flyway from the official website (https://flywaydb.org/).
- For specific databases, JDBC Driver is needed.
Step-by-Step Implementation of Flyway Database Migration Tool
Below are the steps to use Flyway with JDBC for database migration.
Step 1: Directory Structure
Create a directory named db/migration in the project. This is where Flyway will look for migration scripts.
project
└── db
└── migration
└── V1__Initial_Script.sql
Step 2: Migration Script Naming
Migration scripts follow a naming convention. They start with a prefix V, followed by the version number, double underscores, and then a description. For example, V1__Initial_Script.sql.
Step 3: Configuration of Flyway
Create a Flyway configuration file named flyway.conf to specify database connection details and other configurations.
flyway.url=jdbc:mysql://localhost:3306/your_database
flyway.user=your_username
flyway.password=your_password
Now, let us configure Flyway with JDBC in the application. This can be configured by the file named flyway.conf.
Java
import org.flywaydb.core.Flyway;
public class FlywayJdbc
{
public static void main(String args[])
{
Flyway flyway = Flyway.configure()
.load();
flyway.migrate();
}
}
|
In this, it uses Flyway and a database migration tool to perform migrations on a MySQL database. It connects to the database using a specific URL, username, and password, then runs the migrations defined in the Flyway configuration. The migrate()
method is called to execute these migrations.
Step 4: Migration Script
Now, create a simple migration script:
V1__Create_Table.sql:
CREATE TABLE users (
id INT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL
);
Step 5: Run Flyway Migration
Open a terminal and run the following command to execute the migration:
flyway migrate
Flyway will automatically detect and execute the SQL script, updating the database schema.
Share your thoughts in the comments
Please Login to comment...