LoginSignup
0
0

More than 1 year has passed since last update.

Spring Boot で h2database の Embedded モードを使うときはこんな感じ

Last updated at Posted at 2023-04-06

前提

h2database には、3種類の起動モードがある

  • Embedded: データがファイルに保存される
  • In-Memory: データがメモリに保存される(再起動すると消える)
  • Server Mode

この記事は、Embedded を使うときの話。

こんな感じ

application.propeties
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:file:./data/todo
spring.datasource.username=sa
spring.datasource.password=
spring.sql.init.mode=always -- h2database が embedded mode のときはこれを付ける
schema.sql
-- 再起動時の対策でテーブルが存在するなら DROP してから CREATE する
DROP TABLE IF EXISTS memo;
CREATE TABLE memo
(
    id      BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    content TEXT,
);
data.sql
-- schema.sql でテーブルを DROP -> CREATE しているので、再起動しても以下の INSRERT でデータが重複登録されることはない
INSERT INTO memo (content) VALUES ('hoge');
INSERT INTO memo (content) VALUES ('fuga');

ちなみに

ログを出す設定ができるらしい。

application.propeties
spring.datasource.url=jdbc:h2:file:./data/todo;TRACE_LEVEL_FILE=2;TRACE_LEVEL_SYSTEM_OUT=2

Trace Options
The simplest way to enable the trace option is setting it in the database URL. There are two settings, one for System.out (TRACE_LEVEL_SYSTEM_OUT) tracing, and one for file tracing (TRACE_LEVEL_FILE). The trace levels are 0 for OFF, 1 for ERROR (the default), 2 for INFO, and 3 for DEBUG. A database URL with both levels set to DEBUG is:
jdbc:h2:~/test;TRACE_LEVEL_FILE=3;TRACE_LEVEL_SYSTEM_OUT=3

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