什么是H2数据库?
H2数据库是一个轻量级的嵌入式关系型数据库管理系统(RDBMS),它以纯Java编写并且支持内存模式和磁盘模式
嵌入式,划重点
为什么要集成H2数据库?
比如我们想搭一个Demo需要用到数据库,数据库类型并不重要,只要是关系型数据库就可以,这时候便可以考虑集成H2数据库
通常Demo连接数据库有以下几种方式:
数据库安装在本地,连接本地数据库
数据库安装在VM虚拟机,连接虚拟机数据库
拉取Docker镜像,连接容器数据库
以上几种方式中,依鄙人之见拉取docker镜像是最便捷的方式。而集成H2数据库同样便捷,并且会更轻量化
如何集成H2数据库
- 导入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.3.230</version>
</dependency>
- 填写
application.properties配置
# 数据库驱动
spring.datasource.driver-class-name=org.h2.Driver
# 控制台访问
spring.h2.console.enabled=true
# 控制台路径
spring.h2.console.path=/h2-console
# 嵌入式模式
spring.datasource.url=jdbc:h2:mem:testdb
# 默认用户名为sa, 密码为空
spring.datasource.username=sa
spring.datasource.password=
- 可选基于文件的数据初始化
# 初始化数据库
spring.jpa.defer-datasource-initialization=true
# 基于文件
spring.sql.init.schema-locations=classpath:db/schema-h2.sql
spring.sql.init.data-locations=classpath:db/data-h2.sql
例如,可以在resources目录下新建db目录,data-h2.sql中填写DML语句,schema-h2.sql中填写DDL语句
- 启动项目,即可通过浏览器访问H2控制台
网址如下:localhost:端口号/h2-console
例如,我的是:localhost:8081/h2-console
到这里就算集成成功,接下来读者可以试着用ORM框架获取数据写Demo