查看Spring启动的嵌入式H2数据库的内容

tdu*_*eau 47 spring h2

由于以下配置,我想在Web浏览器中查看Spring启动的H2数据库的内容:

<jdbc:embedded-database id="dataSource" type="H2" />

<jdbc:initialize-database data-source="dataSource">
    <jdbc:script location="classpath:db/populateDB.sql"/>
</jdbc:initialize-database>
Run Code Online (Sandbox Code Playgroud)

我在日志中搜索了JDBC URL:

DEBUG o.s.j.d.SimpleDriverDataSource - Creating new JDBC Driver Connection to [jdbc:h2:mem:dataSource;DB_CLOSE_DELAY=-1]
Run Code Online (Sandbox Code Playgroud)

所以我可以填写连接表格如下:

在此输入图像描述

但不幸的是,db仍然是空的,而不应该是由于populateDB.sql脚本.

任何的想法?

谢谢!

hsh*_*hib 48

查看H2或HSQLDB内存数据库的内容几乎相同的问题.

只需在配置中添加以下内容即可.

<bean id="h2Server" class="org.h2.tools.Server" factory-method="createTcpServer" init-method="start" destroy-method="stop" depends-on="h2WebServer">
    <constructor-arg value="-tcp,-tcpAllowOthers,-tcpPort,9092"/>
</bean>
<bean id="h2WebServer" class="org.h2.tools.Server" factory-method="createWebServer" init-method="start" destroy-method="stop">
    <constructor-arg value="-web,-webAllowOthers,-webPort,8082"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

这将在与嵌入式数据库相同的JVM中启动H2 Web控制台和TCP服务器,以便您可以使用Web浏览器访问端口8082(输入jdbc:h2:mem:dataSource as URL),或使用外部SQL客户端访问端口9092比如SQuirreLSQL和查看相同的数据.


chA*_*Ami 21

使用spring boot,您可以在application.properties文件中使用几个配置执行此操作.

spring.h2.console.enabled=true
spring.h2.console.path=/console/
Run Code Online (Sandbox Code Playgroud)

然后,您可以在http:// localhost:8080/console /中访问h2 Web控制台.默认登录配置应该有效,除非您更改它们.

请参阅spring boot 文档.


Tho*_*ler 19

数据库URL jdbc:h2:mem:dataSource表示您正在使用内存数据库.现在,如果您启动第二个Java进程并连接到此数据库,您将最终拥有两个内存数据库(每个进程一个).

如果要连接到现有数据库,则有多个选项:

  • 从同一进程中连接到数据库.不要开始第二个过程.

  • 使用带有硬编码绝对路径的持久数据库,例如:`jdbc:h2:/ data/db/dataSource'.

  • 更复杂/不推荐:如果你开始第二个过程,理论上你可以使用服务器模式连接到内存数据库.但这意味着您需要启动运行测试的服务器.


use*_*985 17

使用Spring Boot时,您可以按如下方式注册H2 Console Servlet:

@Bean
public ServletRegistrationBean h2servletRegistration() {
    ServletRegistrationBean registration = new ServletRegistrationBean(new WebServlet());
    registration.addUrlMappings("/console/*");
    registration.addInitParameter("webAllowOthers", "true");
    return registration;
}
Run Code Online (Sandbox Code Playgroud)

如果您希望控制台远程可用,则重要的一行是addInitParameter设置"webAllowOthers""true".

  • 有关此方法的更多详细信息,请访问:https://springframework.guru/using-the-h2-database-console-in-spring-boot-with-spring-security/ (2认同)

F. *_*rts 13

当您使用带有xml jdbc配置的embeddeb时,数据库的默认名称是'testdb'

尝试在您的网址连接中使用:

jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
Run Code Online (Sandbox Code Playgroud)