Spring Boot | データベースアクセス | Flywayによるマイグレーション
Flywayによるマイグレーション
コードの作成
build.gradle
dependencies {
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
compile 'org.hsqldb:hsqldb'
+ compile 'org.flywaydb:flyway-core'
}
application.properties
spring.jpa.hibernate.ddl-auto=none
src/main/resources/db/migration/V1create_database.sql
CREATE TABLE HOGE (
ID INTEGER NOT NULL IDENTITY,
VALUE VARCHAR(256)
);
INSERT INTO HOGE (VALUE) VALUES ('HOGE');
INSERT INTO HOGE (VALUE) VALUES ('FUGA');
INSERT INTO HOGE (VALUE) VALUES ('PIYO');
Main.java
package sample.springboot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import sample.springboot.jpa.HogeRepository;
@SpringBootApplication
public class Main {
public static void main(String[] args) throws Exception {
try (ConfigurableApplicationContext ctx = SpringApplication.run(Main.class, args)) {
Main m = ctx.getBean(Main.class);
m.method();
}
}
@Autowired
private HogeRepository repository;
public void method() {
this.repository.findAll().forEach(System.out::println);
}
}
実行結果
Hoge [id=0, value=HOGE]
Hoge [id=1, value=FUGA]
Hoge [id=2, value=PIYO]
- Flywayを依存関係に追加すると、サーバー起動時にマイグレーションが実行されます。
- JPAを使用する場合は、JPAがデータベースを自動生成しないように
spring.jpa.hibernate.ddl-auto=noneを指定します。