如何在 Spring Boot 中启用 H2 数据库服务器模式

use*_*859 8 java h2 spring-data-jpa spring-boot

我正在使用带有使用 Spring Boot 的文件的 H2 数据库。

在我的 application.properties 中,我有这个条目:

spring.datasource.url=jdbc:h2:file:c:/Testprojekte/spring-boot-h2-db

但是现在我希望能够在运行应用程序时查看数据库,目前这是不可能的,因为我需要让数据库在服务器模式下运行才能这样做。在文档中,我发现我必须将 AUTO_SERVER=TRUE 添加到 URL 中,但这并不能解决问题。

那么,我需要更改什么才能同时从不同的进程连接到该数据库?

谢谢你的帮助!托尔斯滕

Cep*_*pr0 8

您可以将 H2 TCP 服务器作为 bean 启动:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <!-- <scope>runtime</scope> -->
</dependency>
Run Code Online (Sandbox Code Playgroud)
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean(initMethod = "start", destroyMethod = "stop")
    public Server h2Server() throws SQLException {
        return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9092");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用以下参数从您的 IDE 连接到它(密码 - 空):

url: jdbc:h2:tcp://localhost:9092/mem:testdb
user: sa
Run Code Online (Sandbox Code Playgroud)

更多信息在这里这里


Sma*_* Ma 6

您可以启用 h2 Web 控制台以使用浏览器中的 Web 界面访问内存或文件数据库中的 h2。

因此在 application.properties 中添加以下行:

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
Run Code Online (Sandbox Code Playgroud)

之后重新启动您的spring boot应用程序并检查http://localhost:8080/h2-console您的浏览器。