[英]How to access in-memory h2 database from Intellij IDEA
在 Spring 引导项目中,我试图查看 IDE 中的内存表。
如何从 Intellij IDEA 访问内存中的 h2 数据库。
这是我的application.yml中的一个片段:
h2:
datasource:
url: jdbc:h2:mem:mydb
username: username
password: 123
driver-class-name: org.h2.Driver
init-sql: h2.sql
console:
enabled: true
path: /search/console
settings:
trace: false
web-allow-others: false
Intellij 没有为内存数据库输入用户名的字段: 测试连接显示成功,但它没有看到来自 h2.sql 的表。 我可以使用 h2 控制台访问它们。
请记住,这可能会向您显示数据库而不是表,因为它们只在 h2 控制台中可见。 为了通过 IntelliJ 访问它们,您可能需要将 url 和连接更改为文件类型,而不是 memory 。
所以不是这个:
#spring.datasource.url=jdbc:h2:mem:testdb
你会有这样的事情:
spring.datasource.url=jdbc:h2:file:~/Users/yourUser/IdeaProjects/resume-portal/src/main/resources/data/resume-portal;MV_STORE=false;AUTO_SERVER=TRUE
然后在从 url 创建数据源之后
您现在应该可以看到数据库及其表。
如果您使用新的 url 进行连接,那么它仍然可以从控制台获得。
PS:如果更喜欢使用相对路径,您可以将 url 更改为类似于
jdbc:h2:file:./src/main/resources/data/resume-portal;MV_STORE=false;AUTO_SERVER=TRUE
这是应用程序的 application.yml 文件。
spring.jpa.defer-datasource-initialization=true
#spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.url=jdbc:h2:file:./src/main/resources/data/resume-portal;MV_STORE=false;AUTO_SERVER=TRUE
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.datasource.username=sa
spring.datasource.password=
spring.sql.init.mode=always
我找到了另一种方法。 我创建了H2 Server
bean 并将其添加到我的 SpringBoot 应用程序中。 它看起来像这样:
// Start internal H2 server so can query from IDE
@Bean(initMethod = "start", destroyMethod = "stop")
public Server h2Server() throws SQLException {
return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9092");
}
我的application.properties
上也有以下内容
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.defer-datasource-initialization=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.sql.init.mode=always
# Initialise H2 with H2GIS for spatial support ? see schema-h2.sql also
spring.sql.init.platform=h2
spring.jpa.properties.hibernate.dialect=org.hibernate.spatial.dialect.h2geodb.GeoDBDialect
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
h2.tcp.enabled=true
为了将我的 data.sql 放入 Intellij 的表中,我必须确保我使用了create-drop
并添加了spring.sql.init.mode=always
注意:我使用的是 H2GIS 方言 - 但到目前为止还没有引起任何问题
Intellij
中的连接设置仍然是remote
的,这个字符串jdbc:h2:tcp://localhost:9092/mem:testdb
- 不要忘记将端口更改为9092
我在 Intellij 中连接 window 我还检查了 Schema 下的所有表。 然后在 mem 数据库中存在 H2 的表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.