使用h2数据库时如何“允许远程创建数据库”?

问题描述 投票:0回答:6

我正在尝试使用 H2 数据库创建一个 Spring Boot 项目,其他程序可以访问该数据库。

应用程序属性

spring.datasource.url = jdbc:h2:tcp://localhost:8084/~/./db/tech
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.datasource.initialization-mode=always

SpringBootMyApplication.java

@SpringBootApplication
public class SpringBootMyApplication{

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

    @Bean(initMethod = "start", destroyMethod = "stop")
    public Server h2Server() throws SQLException {
        return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "8084");
    }

}

例外情况是:

Caused by: org.h2.jdbc.JdbcSQLNonTransientConnectionException: Database "C:/Users/onz03589/db/tech" not found, either pre-create it or allow remote database creation (not recommended in secure environments) [90149-200]

如何真正“允许远程创建数据库”?

spring-boot h2
6个回答
8
投票

您需要将

"-ifNotExists"
参数添加到
Server.createTcpServer()
。但是,再次强调,你不应该将它与
"-tcpAllowOthers"
一起使用,除非你的端口受到某种方式的保护。


2
投票

您需要添加 spring boot starter jpa 依赖项以启用

h2
数据库设置的自动配置。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

2
投票

原因可能是

  1. 运行服务器并点击控制台后,spring.datasource.url 未正确填充。复制粘贴 application.properties 文件中的 url
  2. 您可能在属性大写和小写上犯了错误 例如我用过

spring.datasource.driverclassname

而不是

spring.datasource.driverClassName

因此请检查区分大小写的属性名称


1
投票

我在pom.xml中添加了这两个依赖项

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>


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

并在 Application.properties 中添加如下

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

这对我有用。

如果您在创建数据库时需要插入任何表格或数据。您可以通过将.sql文件放在resources目录下来完成

现在,您可以打开数据库 http://localhost:端口/h2-console


1
投票

我创建了一个文件:“application.yml”并添加了以下内容:它有效

spring:
  jpa:
    hibernate:
      ddl-auto: create
    show-sql: true
  datasource:
    driverClassName: org.h2.Driver
    password: ''
    username: sa
    url: jdbc:h2:file:~/h2/userApiValidationAndException 

(userApiValidationAndException 创建您自己的文件)


0
投票

尝试将这些添加到 application.properties 它对我有用

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
© www.soinside.com 2019 - 2024. All rights reserved.