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?

More than 1 year has passed since last update.

SpringでH2データベースを使う[Maven]

Posted at

1.はじめに

Springを勉強するにあたってH2dbで遊ぶことになると思うのですが、H2dbの設定方法をわかりやすく解説します。

2.設定方法

まず、Spring Initializrで依存関係を設定します。
とりあえず、H2, JDBC, Webの3つで問題ないです。
バージョンはSpring boot2.7.1, Java 11 としておきます。
スクリーンショット (42).png

次にH2dbの接続情報をapplication.propertiesに書きます。以下はSpring Data JPAの設定も含まれていますが、JDBCのみの場合は上の2つだけで問題ないです。

application.properties
spring.datasource.url=jdbc:h2:mem:testdb;NON_KEYWORDS=USER
spring.h2.console.enabled=true

spring.data.jpa.repositories.bootstrap-mode=default
spring.jpa.defer-datasource-initialization=true
spring.jpa.show-sql=true

user idやuser passを書くこともできますが、なくても問題ないので省略します。
最後に、テーブルを作成します。resorces直下にdata.sqlを作成します。
スクリーンショット (44).png
data.sqlにSQLを書いていきます。

data.sql
CREATE TABLE person (
	id char(10) NOT NULL,
	name char(100) NOT NULL,
	location char(100) NOT NULL,
	birth_date char(100) NOT NULL,
	primary key(id)
);


INSERT INTO person (id, name, location, birth_date )
VALUES('1',  '山田', '北海道', '20220101');

INSERT INTO PERSON (ID, NAME, LOCATION, BIRTH_DATE )
VALUES('2',  '田中', '東京', '20220202');

INSERT INTO PERSON (ID, NAME, LOCATION, BIRTH_DATE )
VALUES('3',  '佐藤', '沖縄', '20220303');

これで設定は終わりです。

3.実行してみる

Spring Bootを起動させて、H2コンソールをブラウザで開きます。
スクリーンショット (45).png
この画面になったらConnectを押します。(※ログインできないときはapplication.propertiesのURLとH2コンソールURLが違う可能性があります)
ログインができたらテキストボックスのSQLを実行ができれば成功です。
スクリーンショット (46).png

4.最後に

H2dbはSpringで遊ぶ勉強するにはちょうどいいですよね。H2dbの設定方法がわかりにくい記事ばかりだったので書いておきました。

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?