一个棘手的问题是,如果您尝试连接到不存在的 JDBC URL,H2 控制台不会给您错误。相反,它将在该 URL 处创建一个新数据库!要连接到内存数据库,请使用此 JDBC URL(http://localhost:8080/h2-console 是默认控制台):
jdbc:h2:mem:testdb
如果您要输入 jdbc:h2:~/test 之类的内容,则会在您的主目录下创建一个 test.mv 文件。但您的应用程序仍将使用内存数据库。
如果您的 pom 中有 h2 依赖项以及 spring 开发人员工具依赖项,则控制台可用。如果您没有工具依赖项,那么您也可以通过拥有 h2 依赖项并将以下内容添加到您的 application.properties 文件中来查看它:
spring.h2.console.enabled=true #not needed if you have spring-boot-devtools dependency
如果您希望 db 作为文件而不是在内存中,请将以下内容添加到 applications.properties:
spring.datasource.url=jdbc:h2:~/test_db #You will see the file in your home directory.
H2 不适用于持久化数据,但如果您想持久化用于测试目的,请添加:
spring.jpa.hibernate.ddl-auto = update
然后启动应用程序,并在控制台中使用此 JDBC URL:
jdbc:h2:~/test_db
如果您想知道,我在 application.properties 中只有 1 个条目(用于数据库文件),这是我的依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>