2
0

More than 1 year has passed since last update.

SpringBootでh2コンソールに接続ができない

Last updated at Posted at 2022-09-28

SpringBootでh2 databaseをインメモリで使用時、h2-consoleからdb接続ができなかった

エラー内容: Database "mem:testdb" not found, either pre-create it or allow remote database creation (not recommended in secure environments) [90149-214] 90149/90149

環境
IDE: STS3.9.7RELEASE
JAVA: 8
他は下記設定ファイルに

事象発生時の設定ファイル

application.properties
ファイル内容(クリックで展開)
// コンソール使用有効
spring.h2.console.enabled=true
// コンソールパス
spring.h2.console.path=/h2-console
// トレース有無
spring.h2.console.settings.trace=true
// リモートからの接続の是非
spring.h2.console.settings.web-allow-others=false
// 作成するdb名
spring.datasource.url=jdbc:h2:mem:testdb
// dbドライバーのクラス名
spring.datasource.driver-class-name=org.h2.Driver
// ユーザー・パスワード
spring.datasource.username=sa
spring.datasource.password=
build.gradle
ファイル内容(クリックで展開)
plugins {
	id 'org.springframework.boot' version '2.7.4'
	id 'io.spring.dependency-management' version '1.0.14.RELEASE'
	id 'java'
	id 'war'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	runtimeOnly 'com.h2database:h2'
	providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
	useJUnitPlatform()
}

「implementation 'org.springframework.boot:spring-boot-starter-web'」と
「runtimeOnly 'com.h2database:h2'」はh2コンソールの起動時に必要になるライブラリになります。

setting.gradle
ファイル内容(クリックで展開)
rootProject.name = 'JavaRestApi'

解決策1. build.gradleに以下を追加し、IDEのコンソールログでJDBC URLを確認する

追加する内容(クリックで展開)
implementation 'org.springframework.boot:spring-boot-starter-jdbc'

これで、IDE(総合開発環境)のログに
「INFO 17824 --- [ main] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:○○○○-○○'」
などと表示されるので、'jdbc:h2:mem:○○'をJDBC URLにコピーして接続できる。

上記「application.properties」の「作成するdb名」を指定しているのに、全然違うものになる原因は、Spring Bootのバージョンによっては、デフォルトでスキーマ名がランダムに生成される設定になっているため

解決策2. スキーマがランダムに生成される設定をオフにする

application.properties に以下を追記
spring.datasource.generate-unique-name=false

これでスキーマがランダムに生成されず、"testdb"での生成ができる。
コンソールに表示されるJDBC URLも次のようになった
「INFO 17824 --- [ main] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'」

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