如何在 Spring Boot 使用 H2 Embedded DB 簡單筆記
· 3 分鐘閱讀
Embedded DB 是很好用的工具,有時候為了一個小專案還要特別去 PostgreSQL 或 MySQL 建 database 會覺得殺雞焉用牛刀,如果只用文字檔處理又覺得不足,建個微型 DB 直接包在 Spring Boot 的專案中就很適合了
Spring Boot 支援的 Embedded DB 有三種
- Derby
- H2
- HyperSQL
網路有些比較文,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'
}