我正在尝试使用 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]
如何真正“允许远程创建数据库”?
您需要将
"-ifNotExists"
参数添加到 Server.createTcpServer()
。但是,再次强调,你不应该将它与 "-tcpAllowOthers"
一起使用,除非你的端口受到某种方式的保护。
您需要添加 spring boot starter jpa 依赖项以启用
h2
数据库设置的自动配置。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
原因可能是
spring.datasource.driverclassname
而不是
spring.datasource.driverClassName
因此请检查区分大小写的属性名称
我在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
我创建了一个文件:“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 创建您自己的文件)
尝试将这些添加到 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