This guide shows how to use
Flyway for managing schema migrations in a
Spring Boot project with an
Apache Derby database.
1. Add Dependencies
In
pom.xml
:
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2. Configure Derby and Flyway
In
application.properties
:
spring.datasource.url=jdbc:derby:memory:migrateDB;create=true
spring.datasource.driver-class-name=org.apache.derby.jdbc.EmbeddedDriver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=none
spring.flyway.enabled=true
spring.flyway.locations=classpath:db/migration
Set
ddl-auto=none
so schema changes come only from Flyway.
3. Create Migration Script
Create file:
src/main/resources/db/migration/V1__create_users.sql
CREATE TABLE users (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255)
);
Flyway will apply this script at startup.
4. Create Entity
import jakarta.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// getters and setters
}
5. Repository
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
6. REST Controller
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
private final UserRepository repo;
public UserController(UserRepository repo) {
this.repo = repo;
}
@PostMapping
public User add(@RequestBody User user) {
return repo.save(user);
}
@GetMapping
public List<User> all() {
return repo.findAll();
}
}
7. Run Migration
Run Spring Boot:
mvn spring-boot:run
Flyway will detect the Derby database, run
V1__create_users.sql
, and track migrations in the
flyway_schema_history
table.
image quote pre code