【问题标题】:Default configuration of H2 in-memory database set up by SpringbootSpringboot设置的H2内存数据库默认配置
【发布时间】:2021-01-06 08:18:28
【问题描述】:

我正在使用带有 Spring Boot(版本 2.3.3.RELEASE)的 H2 数据库以及 H2 数据库的所有默认设置。

这是我的应用程序的所有文件。

pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.3.RELEASE</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

application.properties

spring.h2.console.enabled=true

Application.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.sql.SQLException;

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

}

当我尝试使用以下凭据连接 H2 数据库(由 springboot 配置并启动所有默认配置)时启动应用程序后,

我说错了

找不到数据库“mem:testDB”,请预先创建或允许远程 创建数据库

如何使用所有默认凭据连接到由 Spring Boot 配置和启动的 H2 数据库。

我不想覆盖application.properties 文件中的任何配置,spring.h2.console.enabled=true 除外。

【问题讨论】:

  • 试试小写:jdbc:h2:mem:testdb
  • 你提供的 spring.datasource.url 值是什么,基于它将配置内存数据库
  • 我没有提供任何像“spring.datasource.url”这样的属性。我想让 spring 使用默认配置配置数据库。 @Selindek:我也尝试使用小写的“jdbc:h2:mem:testdb”,但仍然出现相同的错误
  • 尝试 jdbc:h2:~/test 因为 h2 会自动在您的用户目录下创建一个测试数据库。查看快速入门:h2database.com/html/quickstart.html

标签: java spring-boot h2 in-memory-database


【解决方案1】:

在较新版本的 Spring Boot (2.2+) 中,在控制台上查找以下日志消息:Use the JDBC URL to connect on /h2-console 页面:

Spring Boot 2.2+:

INFO H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'

Spring Boto 2.3+:

INFO H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:621dd224-01db-4137-807f-b9c3046de64d'

【讨论】:

  • 答案是正确的,表名显示在spring init log中。
【解决方案2】:

仅启用控制台是不够的,您还需要提及您要连接的数据库。在您的情况下,如果您想在内存数据库中连接,请添加以下属性,然后尝试使用相同的凭据连接您的内存数据库

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

【讨论】:

    猜你喜欢
    • 2012-10-21
    • 2014-07-15
    • 2011-01-06
    • 2012-12-21
    • 2021-06-05
    • 1970-01-01
    • 2021-11-19
    • 2017-01-05
    • 1970-01-01
    相关资源
    最近更新 更多