How to connect H2 console to embedded Spring H2 DB

2020-04-20 12:32发布

问题:

Ok, Im developing simple app, which has Spring Ebedded H2 database for development. database.xml bean conf looks like this:

<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>

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

H2 database is initializing, My app is working, Im creating entities, and they are stored in H2 db when Tomcat is launched (I know it because I use and retrieve them). However, when I look at H2 console, my Entity tables are not present.

I guess H2 console points on another H2 database, and Spring Embedded H2 Db is not related with that H2 console.

How to fix that?

EDIT: Im getting access to H2 console by typing http://localhost:8082 in my web browser.

回答1:

if your application is not spring boot than you need to add below servlet configuration in web.xml file

!-- H2 Database Console for managing the app's database -->
<servlet>
    <servlet-name>H2Console</servlet-name>
    <servlet-class>org.h2.server.web.WebServlet</servlet-class>
    <init-param>
        <param-name>-webAllowOthers</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>H2Console</servlet-name>
    <url-pattern>/admin/h2/*</url-pattern>
</servlet-mapping>

<!-- Handles requests into the application -->

please see more details https://github.com/spring-projects/greenhouse/blob/master/src/main/webapp/WEB-INF/web.xml

and if your application is spring boot based than you have to follow https://springframework.guru/using-the-h2-database-console-in-spring-boot-with-spring-security/