如何在 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'
}