[英]What is the default name of embedded H2 database in Spring Boot?
As I've read the default name of the embedded H2 database in Spring Boot should be testdb
, but if I try to connect to with the H2 Console, I get the following error:因为我已经阅读了 Spring Boot 中嵌入式 H2 数据库的默认名称应该是
testdb
,但是如果我尝试连接到 H2 控制台,我会收到以下错误:
Database "mem:testdb" not found, either pre-create it or allow remote database creation (not recommended in secure environments)
未找到数据库“mem:testdb”,要么预先创建它,要么允许远程创建数据库(不推荐在安全环境中使用)
It works only if I set the name explicitly in the application.properties
with the following parameter:仅当我在
application.properties
使用以下参数显式设置名称时才有效:
spring.datasource.url=jdbc:h2:mem:testdb
Since the application can connect to the embedded database without this configuration, there must be a different default name.由于应用程序可以在没有此配置的情况下连接到嵌入式数据库,因此必须有一个不同的默认名称。 But what is the default name of the automatically configured database?
但是自动配置的数据库的默认名称是什么?
Enable h2 console in application.properties as jurez said如 jurez 所说,在 application.properties 中启用 h2 控制台
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.jpa.show-sql=true
and then when you run the application in the console you will see something like this:然后当您在控制台中运行应用程序时,您将看到如下内容:
H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:2f5b7da9-0cd2-4fdd-98d2-5ef5f76391bc'
then you can use this JDBC URL to connect to the database from the h2-console然后你可以使用这个 JDBC URL 从 h2-console 连接到数据库
http://localhost:8080/h2-console
jdbc:h2:mem:2f5b7da9-0cd2-4fdd-98d2-5ef5f76391bc
you can specify your own name by adding the following property in the application.property file您可以通过在 application.property 文件中添加以下属性来指定自己的名称
spring.datasource.url=jdbc:h2:mem:testdb
remember since this is an in-memory database it will be dropped and recreated every time you run your application请记住,因为这是一个内存数据库,每次运行应用程序时都会删除并重新创建它
h2 also has a persistent mode but it is not recommended, you can do that by adding the following configurations taken from the following tutorial Spring Boot and H2 in memory database - Why, What and How? h2 也有一个持久模式,但不推荐,您可以通过添加从以下教程Spring Boot 和内存数据库中的 H2 中获取的以下配置- 为什么,什么和如何?
spring.datasource.name=yourdbname
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.initialize=false
spring.datasource.url=jdbc:h2:file:~/yourdbname;DB_CLOSE_ON_EXIT=FALSE;IFEXISTS=TRUE;DB_CLOSE_DELAY=-1;
spring.jpa.hibernate.ddl-auto = update
By default, memory databases are only accessible to the process in which they are running.默认情况下,内存数据库只能被它们运行的进程访问。
If you want to access it from H2 Console, you need to enable it in application.properties:如果你想从 H2 Console 访问它,你需要在 application.properties 中启用它:
spring.h2.console.enabled=true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.