0
1

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データベース(インメモリ)の中身を確認するアプローチまとめ

0
Posted at

Spring Bootの開発で手軽に使えるH2データベースって
DockerとかローカルにPostgreSQLとか入れなくていいので楽ですよね
本来DBの中を確認するならCLIとかCUIツールなど使うと思いますが、
H2だとブラウザで確認するってことを知ったので備忘録として残しておきます。

ちなみに今回はH2データベースの中身を確認するための基本的なブラウザアクセスから、
Spring Securityによるブロックの解除方法までをご紹介します。

1. 前提

今回は、以下のようにインメモリ(mem)でH2データベースを設定している状態を前提とします。

application.properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

# H2コンソールを有効化
spring.h2.console.enabled=true

pom.xml
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
</dependency>

注意点: インメモリデータベース(mem)のため、Spring Bootアプリを停止・再起動するとデータはすべてリセットされます。

2. ブラウザから確認する(H2コンソール)

もっとも標準的で簡単な方法です。

  1. Spring Bootアプリケーションを起動します。
  2. ブラウザで http://localhost:8080/h2-console にアクセスします。(※ポート番号を8081などに変更している場合は、ご自身の環境に合わせてください)
  3. ログイン画面が表示されたら、以下のように入力します。
項目 入力値 備考
JDBC URL jdbc:h2:mem:testdb ※初期値から変更が必須!間違えやすいポイントです。
User Name sa application.propertiesで指定したユーザー名
Password (空欄) application.propertiesで指定したパスワード

「Connect」を押すと、データベースのコンソール画面に入り、SQLを実行できます。

image.png
※デフォルトはEnglishです。日本語もちゃんとあるので、使いたい方は変更してください

3. 【重要】「localhost で接続が拒否されました」と出る場合の対処法

プロジェクトに Spring Security を導入している場合、ログイン画面で「Connect」を押した直後に画面が真っ白(またはグレー)になり、接続拒否エラー(ERR_CONNECTION_REFUSED)になることがあります。

これは、H2コンソールが画面描画に iframe を使用しており、Spring Securityのデフォルト設定(クリックジャッキング対策)が iframe の表示をブロックしてしまうことが原因です。

解決策:SecurityFilterChainの設定を追加する

以下の設定クラスを追加し、H2コンソールへのアクセス許可と iframe の許可(同一オリジンのみ)を行います。

※Spring Boot 3.x (Spring Security 6.x) 向けの記述です。

SecurityConfig.java
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        
        // 1. H2コンソールのパスへのアクセスを許可
        http.authorizeHttpRequests(auth -> auth
            .requestMatchers(PathRequest.toH2Console()).permitAll()
            // ※他のエンドポイントのセキュリティ要件は適宜追加してください
            .anyRequest().permitAll() 
        );

        // 2. H2コンソールに対するCSRF保護を無効化
        http.csrf(csrf -> csrf
            .ignoringRequestMatchers(PathRequest.toH2Console())
        );

        // 3. H2コンソールの iframe 表示を許可(同一オリジンのみ)
        http.headers(headers -> headers
            .frameOptions(frame -> frame.sameOrigin())
        );

        return http.build();
    }
}

これでアプリを再起動すれば、無事にH2コンソールが開くようになります。

まとめ

  • 基本はブラウザの http://localhost:8080/h2-console から確認。
  • 接続拒否される場合は Spring Securityのiframe設定 を疑う。

開発時のデバッグにお役立てばと思います

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?