Spring Boot 2.x 之 H2 数据库

1. Spring Boot下H2数据库的常用配置项

# 指定数据库的类型
spring.datasource.platform=h2

# 数据库连接地址(文件模式)
## AUTO_SERVER=TRUE,启动自动混合模式,允许开启多个连接,该参数不支持在内存中运行模式
## DB_CLOSE_ON_EXIT=FALSE,当虚拟机退出时并不关闭数据库
spring.datasource.url=jdbc:h2:file:./h2/code-generator;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE
## 内存模式示例
# spring.datasource.url=jdbc:h2:mem:testdb

# 数据库驱动
spring.datasource.driver-class-name=org.h2.Driver

# 用户名
spring.datasource.username=testdb

# 密码
spring.datasource.password=test

# 是否启用H2控制台
spring.h2.console.enabled=true

# H2控制台的访问路径, 缺省是/h2-console
spring.h2.console.path=/h2-console

# 是否允许远程访问H2
spring.h2.console.settings.web-allow-others=true

关于连接URL中的DB_CLOSE_ON_EXIT=FALSE

Don't Close a Database when the VM Exits.
By default, a database is closed when the last connection is closed. However, if it is never closed, the database is closed when the virtual machine exits normally, using a shutdown hook. In some situations, the database should not be closed in this case, for example because the database is still used at virtual machine shutdown (to store the shutdown process in the database for example). For those cases, the automatic closing of the database can be disabled in the database URL. The first connection (the one that is opening the database) needs to set the option in the database URL (it is not possible to change the setting afterwards).

2. h2的内存模式与本地模式

本地文件模式

spring.datasource.url=jdbc:h2:file:~/testdb

该例子中的~是用户目录。

内存模式

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

内存模式时,应用关闭则数据库同时关闭,数据库中的数据也就清空了。

3. H2的控制台

控制台界面如下:

端口号

访问H2的控制台时,URL中的端口号就是所在应用的端口号

路径

访问H2的控制台的路径后缀是spring.h2.console.path配置项的值,默认是/h2-console

Driver Class

org.h2.Driver

JDBC URL

填配置项spring.datasource.url的值

用户名密码

application.properties中配置的值对应。

原文地址:https://www.cnblogs.com/zyon/p/11055579.html