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?

Spring Boot × H2入門:H2データベースの設定

Posted at

H2データベースとは

java製の超軽量RDBMS。JARひとつで動き、ローカル開発・検証・単体テストに最適。

H2データベースの依存関係を追加

Mavenの場合

pom.xmlファイルに以下の依存関係を追加する。

<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <scope>runtime</scope>
</dependency>

Gradle(Groovy)の場合

build.gradleファイルに以下の依存関係を追加する。

dependencies {
    implementation 'com.h2database:h2'
}

H2コンソールの有効化

H2コンソールの有効化とは、H2が持つ軽量な"Web UI(SQL実行&テーブル閲覧ツール)"をSpring Bootアプリ上で使えるようにする設定のこと。本番では無効が原則。
application.propertiesに以下の設定を追加する。

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

アクセスは、アプリ起動後に http://localhost:8080/h2-console を開き、画面で JDBC URL に jdbc:h2:mem:testdb を入れて「Connect」をクリック。

データベース接続の設定

application.propertiesに以下の設定を追加する。

spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

ログにSQLを表示する(おすすめ構成)

application.propertiesに以下の設定を追加する。

spring.jpa.show-sql=

役割:JPAが生成するSQLクエリをコンソールに表示するかを制御する。
・true:SQLクエリをコンソールに表示する。
・false:SQLクエリをコンソールに表示しない(デフォルト)。

spring.jpa.show-sql=true

spring.jpa.properties.hibernate.format_sql=

役割:Hibernateが生成するSQLクエリを整形する。
・true:整形されたSQLクエリを出力する。
・false:整形せず、そのまま出力する(デフォルト)。

spring.jpa.properties.hibernate.format_sql=true

@Entityからテーブルを自動生成/更新

@Entityを使ってクラスを定義すると、Spring Bootがデータベースに対応するテーブルを自動生成します。
application.propertiesに以下の設定を追加する。

spring.jpa.hibernate.ddl-auto=update

ddl-autoの値にはupdateの他にnone、validate、create、create-dropなどがあります。
注意:update は開発向け。本番は validate/none + Flyway/Liquibase を推奨。

ファイル型H2/MySQL互換モード

永続化したい(アプリ再起動でも残す):

spring.datasource.url=jdbc:h2:file:./.localdb/appdb;AUTO_SERVER=TRUE

MySQLっぽく試す(完全互換ではない点に注意):

spring.datasource.url=jdbc:h2:mem:testdb;MODE=MySQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE

MODE=MySQL は全互換ではないため、最終確認は実DB or Testcontainers推奨。

Spring Security(Boot 3)の最低限設定

デフォルトだと /h2-console/** がブロックされます。フレーム許可 & CSRF無効化を追加。

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
      .csrf(csrf -> csrf.ignoringRequestMatchers("/h2-console/**"))
      .headers(h -> h.frameOptions(f -> f.sameOrigin()))
      .authorizeHttpRequests(auth -> auth
          .requestMatchers("/h2-console/**").permitAll()
          .anyRequest().authenticated()   // 必要に応じて変更
      );
    return http.build();
}

本番ではH2コンソール無効が原則(spring.h2.console.enabled=false)。外部公開しないこと。

インメモリDB(H2)の仕組み

H2データベースはデータベースをメモリ上に持ちます。そのため、Spring Boot起動中のみデータベースを利用することができ、Spring Bootを再起動したり、メモリがクリアされるとデータが消えてしまいます。

まとめ

• H2は開発最速セットアップに最適。
• H2コンソールは開発限定で有効化し、Securityを適切に設定。

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?