跳至主要内容

如何在 Spring Boot 使用 H2 Embedded DB 簡單筆記

· 3 分鐘閱讀
Eric Cheng

Embedded DB 是很好用的工具,有時候為了一個小專案還要特別去 PostgreSQL 或 MySQL 建 database 會覺得殺雞焉用牛刀,如果只用文字檔處理又覺得不足,建個微型 DB 直接包在 Spring Boot 的專案中就很適合了

Spring Boot 支援的 Embedded DB 有三種

  • Derby
  • H2
  • HyperSQL

Spring Boot Embedded DB

網路有些比較文,ex: 文章一文章二,沒有很認真去比較,但看起來大致上差異不大,而 H2 使用的人稍微多一點,效能稍微好一點,所以就選 H2 來用

新增 build.gradle 內容

在 build.gradle 新增一行

runtimeOnly 'com.h2database:h2'

這個測試專案使用 web,完整 dependencies 如下

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'com.h2database:h2'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

新增 application.properties 內容

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

啟動專案

這時將專案啟動後,直接點選 http://localhost:8080/h2-console/ 就可以看到以下畫面

H2-Console

填入 application.properties 設定的內容,點選「Connect」,就可以成功登入

H2-Console 2

如何建立新的 database

文件中預設使用的是 datasource 是使用記憶體

spring.datasource.url=jdbc:h2:mem:testdb

實務上不太實用,你總不希望記憶體一但清空,資料就不見吧,H2 提供使用檔案儲存的選項

首先參考官方文件:Creating New Databases

先找到 h2 的 jar 檔,如果是使用 gradle 的話,一般就在 gradle 的目錄,直接在 cmd 執行官方文件的指令就可以建新的 database

> java -cp h2-*.jar org.h2.tools.Shell

Welcome to H2 Shell
Exit with Ctrl+C
[Enter] jdbc:h2:mem:2
URL jdbc:h2:./path/to/database
[Enter] org.h2.Driver
Driver
[Enter] sa
User your_username
Password (hidden)
Type the same password again to confirm database creation.
Password (hidden)
Connected

sql> quit
Connection closed

建出來的檔案檔名為 xxxx.mv.db,假設你把檔案放在 windows 的目錄 c:\ooo\ 下,只要修改 application.properties 的設定

spring.datasource.url=jdbc:h2:file:c:/ooo/xxxx

就可以讀到 c:\ooo\xxxx.mv.db 的資料

如何在讀取其他電腦的 H2 DB

在 Spring Boot 啟動的 H2 DB 如果用剛才說的 http://localhost:8080/h2-console/ 只能在本機讀到資料,在開發階段沒有問題,但如果放到測試環境,別的使用者要在本機讀取測試環境的資料就會是 404

再修改 application.properties,增加兩行

spring.h2.console.enabled=true
spring.h2.console.settings.web-allow-others=true

這樣別台電腦也可以使用 h2-console 讀取 H2 DB 的資料了



版權聲明


這是 google 廣告