🤖
AI Answer
### Step 1: Set Up Your Java Project
1. **Create a new Java project** (using your preferred IDE like IntelliJ IDEA or Eclipse).
2. **Add Maven or Gradle as your build tool.** If you are using Maven, create a `pom.xml` file. For Gradle, create a `build.gradle` file.
### Step 2: Include Flyway Dependency
- **For Maven:** Add the following dependency in your `pom.xml`:
```xml
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>9.16.0</version>
</dependency>
```
- **For Gradle:** Add the following line in your `build.gradle`:
```groovy
implementation 'org.flywaydb:flyway-core:9.16.0'
```
### Step 3: Configure Flyway
1. **Create a configuration file (application.properties or application.yml)** in the `src/main/resources` directory.
2. **Add the following properties for PostgreSQL:**
```properties
flyway.url=jdbc:postgresql://localhost:5432/your_database_name
flyway.user=your_username
flyway.password=your_password
```
### Step 4: Create a Migration Script
1. **Create a directory for migrations:** Create a folder named `db/migration` under `src/main/resources`.
2. **Add a SQL migration file:** Create a file named `V1__Create_table.sql` in the `db/migration` directory with the following content:
```sql
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL
);
```
### Step 5: Run Flyway Migrations
1. **Create a main Java class (e.g., `Application.java`):**
```java
import org.flywaydb.core.Flyway;
public class Application {
public static void main(String[] args) {
Flyway flyway = Flyway.configure().load();
flyway.migrate();
System.out.println("Database migration completed successfully!");
}
}
```
2. **Run your application:** This will apply the migration to your PostgreSQL database.
### Step 6: Verify the Migration
- Use a PostgreSQL client or tool (like pgAdmin) to connect to your database and verify that the `users` table has been created successfully.
### Additional Notes
- Make sure your PostgreSQL server is running.
- Adjust the database URL, username, and password in your configuration to match your PostgreSQL setup.
- Always back up your database before running migrations in a production environment.
### Resources
- [Flyway Documentation](https://flywaydb.org/documentation/)
- [PostgreSQL Documentation](https://www.postgresql.org/docs/)
Categories:
programming,
java,
database,
Java,
PostgreSQL,
Flyway,