如何从 Intellij IDEA 访问内存中的 h2 数据库

2022-09-03 02:57:12

在Spring Boot项目中,我试图从我的IDE中查看内存中的表。

如何从 Intellij IDEA 访问内存中的 h2 数据库。

以下是我的应用程序.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 没有用于输入内存中数据库用户名的字段:Intellij has no field to input username for in-memory database测试连接显示成功,但它看不到来自 h2.sql 的表。我可以使用h2控制台访问它们。


答案 1

请记住,这可能会向您显示数据库,但不会显示表,因为它们仅在h2控制台中可见。要通过 IntelliJ 访问它们,您可能需要将 url 和连接更改为文件类型,而不是在内存中

所以不是这个:

#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创建数据源之后

enter image description here

enter image description here

现在,您应该会同时看到数据库及其表。

enter image description here

如果您使用新网址进行连接,则控制台仍然可以使用。

enter image description herePS:如果更喜欢使用相对路径,则可以将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

答案 2

默认情况下,IntellJ不显示任何数据库。

enter image description here

  1. right click在 然后选择datasourceProperties

enter image description here

  1. 在选项卡中,您将看到一个列表,用于选择应显示的内容(我通常选择 )。选择您需要显示的内容SchemasoptionsdatabaseAll databasesdatabase

enter image description here

结果:

enter image description here


推荐