0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flywayを導入する(SpringBoot + Maven)

Posted at

Flywayとは

Flywayとはデータベースのマイグレーションツールです。
DDLや初期データをFlyway経由で投入することで、

  • DB環境(ステージング環境や本番環境など)ごとにそれらがどこまで適用されているかバージョン管理ができる
  • 新たにDB構築する際にもコマンド1つ、あるいは自動で同じ手順を適用し構築できる
  • テスト環境のDBを毎回リセットし残骸データのない状態で検証ができる

などのメリットがあります。

今回初めて構築しましたのでその手順をここに記録したいと思います。

環境紹介

今回は以下の環境で構築しました。

  • Spring Boot 3.5.0
  • Apache Maven 3.9.10
  • Flyway 11.7.2
  • Postgresql 17.3

導入方法

以下2つの方法を試しましたのでそれぞれご紹介したいと思います。

  1. Spring Boot経由で導入する
  2. Mavenプラグイン経由で導入する

SQLファイルの準備

まずはいずれの手順でも必要になるSQLファイルの準備について先に解説します。

Flywayのデフォルト設定に従い、
src/main/resource配下にdb/migrationディレクトリを作成しそこに格納します。
作成するファイル名は以下のルールに則ってください。

V(固定) + {バージョン} + __(半角アンダーバー2つ) + 任意の名称.sql

例)

  • V1_0_0__create_student.sql
  • V1.0.0__create_student.sql
  • V001__create_student.sql

※先頭の「V」はFlywayの命名規則で決まっています。
※バージョンは「_(アンダーバー)」、もしくは「.(ドット)」で区切ることが可能です。
※バージョンの数値が小さい順にクエリは実行されます。

ここではサンプルとしてstudentというテーブルを作成、初期データを登録するようにします。

V001__create_student.sql
CREATE TABLE student (
  id bigserial PRIMARY KEY,
  name varchar(60) NOT NULL,
  update_time timestamp NOT NULL DEFAULT current_timestamp,
  create_time timestamp NOT NULL DEFAULT current_timestamp
);
V002__insert_student.sql
INSERT INTO student (id, name)
VALUES (100, 'yamada');

それではここから各導入方法についてご説明します。

1. Spring Boot経由で導入する

pom.xml

pom.xmlにpostgresql用の依存関係としてflyway-database-postgresqlを追加します。
Flyway10.0以降はflyway-coreではなくこちらを設定すれば良いです。
これによりflyway-coreも自動的に追加されます。
使用しているDBに応じて追加する依存関係は変更してください。

pom.xml
    <dependencies>
		<dependency>
			<groupId>org.flywaydb</groupId>
			<artifactId>flyway-database-postgresql</artifactId>
		</dependency>
	</dependencies>

設定ファイル

設定の記載場所はapplication.propertiesですが、
結論から言うと最低限の設定でよければ特に作業は不要です。

FlywayがDB接続する際の情報はアプリケーション側の設定(spring.datasource.urlなど)を参照可能ですし、
Flywayの有効/無効を示すspring.flyway.enabledもデフォルトでtrueになっています。

各種設定についてはSpring Bootのリファレンスをご参照いただければと思います。

実行する

設定は以上で完了です。
Spring Bootアプリケーション起動時に自動でマイグレーションが走るので、
アプリケーションを起動後、DBに接続してテーブル一覧を確認してみます。

Flyway用のテーブルflyway_schema_historyと、事前準備したstudentテーブルが作成されています。

postgres=# \dt
                 List of relations
 Schema |         Name          | Type  |  Owner   
--------+-----------------------+-------+----------
 public | flyway_schema_history | table | postgres
 public | student               | table | postgres
(2 rows)

flyway_schema_historyselectすると現在の反映状況が確認でき、
先ほどの2つのクエリが反映されていることがわかります。

postgres=# select * from flyway_schema_history;

 installed_rank | version |  description   | type |          script          |  checksum  | installed_by |        installed_on        | execution_time | success 
----------------+---------+----------------+------+--------------------------+------------+--------------+----------------------------+----------------+---------
              1 | 001     | create student | SQL  | V001__create_student.sql |  470394996 | postgres     | 2025-07-06 23:59:54.306231 |              4 | t
              2 | 002     | insert student | SQL  | V002__insert_student.sql | -562349985 | postgres     | 2025-07-06 23:59:54.321683 |              2 | t
(2 rows)

念のためstudentテーブルもselectするとレコードが登録されていることが確認できました。

postgres=# select * from student;

 id  |  name  |        update_time         |        create_time         
-----+--------+----------------------------+----------------------------
 100 | yamada | 2025-07-06 23:59:54.324711 | 2025-07-06 23:59:54.324711
(1 row)

2. Mavenプラグインを使用し導入する

こちらの方法では上記の手順に加えてMavenプラグインを追加することで、
アプリケーションを起動せずコマンドでFlywayを操作することが可能になります。
DB接続せずともバージョン確認できたり、コマンド一つで初期化することが可能です。

設定ファイル

こちらの方法ではsrc/main/resource配下に設定ファイルとしてflyway.propertiesを作成します。
最低限の設定であればapplication.propertiesに記載しているアプリケーション向け設定と限りなく同じです。

flyway.properties
flyway.url=jdbc:postgresql://{ホスト名}:{ポート番号}/{データベース名}
flyway.user={ユーザー名}
flyway.password={パスワード}

pom.xml

まずはSpring Boot経由の場合と同様、pom.xmlflyway-database-postgresqlを追加します。

さらにここではFlyway用のプラグインを追加します。
この時設定の読み込み先として先ほど作成したflyway.propertiesを設定します。
設定ファイルを読み込まずタグで直接各種設定することもできますが、ここでは外出ししておきます。

pom.xml
	<build>
		<plugins>
			<plugin>
				<groupId>org.flywaydb</groupId>
				<artifactId>flyway-maven-plugin</artifactId>
				<configuration>
    				<configFiles>
                            <configFile>src/main/resources/flyway.properties</configFile>
					</configFiles>
				</configuration>
			</plugin>
		</plugins>
	</build>

実行する

flywayコマンドを使用していきます。

まずはマイグレーションから。
(mvnコマンドが使用可能なディレクトリで実行します。)
事前準備した2ファイルの実行に成功したとのログが出力されています。

> mvn flyway:migrate

[INFO] --- flyway:11.7.2:migrate (default-cli) @ demo ---
[INFO] Database: jdbc:postgresql://localhost:5432/database (PostgreSQL 17.3)
[INFO] Schema history table "public"."flyway_schema_history" does not exist yet
[INFO] Successfully validated 2 migrations (execution time 00:00.006s)
[INFO] Creating Schema History table "public"."flyway_schema_history" ...
[INFO] Current version of schema "public": << Empty Schema >>
[INFO] Migrating schema "public" to version "001 - create student"
[INFO] Migrating schema "public" to version "002 - insert student"
[INFO] Successfully applied 2 migrations to schema "public", now at version v002 (execution time 00:00.005s)

そして現状況の確認です。
flyway_schema_historyと同様に準備したファイル分の行数が出力されています。
StateがSuccessになっており、Installed Onにマイグレーション実行した日時が入っています。

> mvn flyway:info

[INFO] +-----------+---------+----------------+------+---------------------+---------+----------+
| Category  | Version | Description    | Type | Installed On        | State   | Undoable |
+-----------+---------+----------------+------+---------------------+---------+----------+
| Versioned | 001      | create student | SQL  | 2025-07-05 17:12:48 | Success | No       |
| Versioned | 002      | insert student | SQL  | 2025-07-05 17:12:48 | Success | No       |
+-----------+---------+----------------+------+---------------------+---------+----------+

最後に今構築したDBを初期化してみます。
こちらはflyway.propertiesにてflyway.clearDisabled=falseと設定していないと実行できません。(デフォルト値がtrueになっているため)

本番環境などでは誤って初期化してしまうと危険なため設定しない方が良いと思いますが、
テスト環境で初期データベースに戻したい時などに使用すると良いかと思います。

> mvn flyway:clean

[INFO] --- flyway:11.7.2:clean (default-cli) @ demo ---
[INFO] Database: jdbc:postgresql://localhost:5432/demo_database (PostgreSQL 17.3)
[INFO] Successfully dropped pre-schema database level objects (execution time 00:00.000s)
[INFO] Successfully cleaned schema "public" (execution time 00:00.018s)
[INFO] Successfully cleaned schema "public" (execution time 00:00.004s)
[INFO] Successfully dropped post-schema database level objects (execution time 00:00.000s)

再度flyway:infoを実行してみるとStateがPendingになっており、
先ほどは時間が表示されていたInstalled Onが空欄になっていることがわかります。

> mvn flyway:info

[INFO] +-----------+---------+----------------+------+--------------+---------+----------+
| Category  | Version | Description    | Type | Installed On | State   | Undoable |
+-----------+---------+----------------+------+--------------+---------+----------+
| Versioned | 001      | create student | SQL  |              | Pending | No       |
| Versioned | 002      | insert student | SQL  |              | Pending | No       |
+-----------+---------+----------------+------+--------------+---------+----------+

まとめ

今回はSpring Boot + Maven環境におけるFlywayの導入方法を2つご紹介しました。

Spring Boot経由での導入

  • 手順が非常にシンプルで導入しやすい

Mavenプラグイン経由での導入

  • Flywayコマンドが利用可能になりアプリケーションを起動せずとも操作できる
  • 手動でFlywayの操作ができる
  • 設定箇所が増える、分散してしまう

今回は導入方法のみですが、
ソースコードからFlywayを使用しテストコード実行前に任意のデータを投入したり、初期化したりといったことも可能なようです。
それら詳しい使用方法についても今後学習し、使いこなしていきたいと思います。

それでは。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?