How to show content of local h2 database(web console)?

后端 未结 3 738
予麋鹿
予麋鹿 2021-02-07 04:55

Recently I joined a new team and here guys use h2 for stub service.

I was wondering whether I can show the content of this database using web interface. At work it is av

3条回答
  •  难免孤独
    2021-02-07 05:38

    Let's split the question into two parts.

    Depending on how you specify the connection to H2, you'll get different operational modes.

    Modes are: Embedded, In-Memory, Server.

    jdbc:h2:~/test gives you a H2 instance in embedded mode. The embedded mode has a limitation of being accessible only through the same class loader and same JVM (proof)

    jdbc:h2:mem:test gets you an in-memory H2 instance. That is also not accessible from outer world.

    jdbc:h2:tcp://localhost/test will start H2 server and it will be accessible from outside of JVM server mode but with one limitation - the server needs to be started before the connection is made.

    The last limitation is causing your Connection refused: connect: localhost" exception.

    To sum everything up:

    • start the H2 server before you start application
    • use jdbc:h2:tcp://localhost/test as connection string
    • ....
    • happy coding :)

    Update

    Just noticed that you want to start the server in the process of launching application.

    You can do that in several ways, depending how do you start the application:

    • If you're using maven / gradle it's easier for you to add some profile / task so that it gets executed before the application actually starts.
    • If you have to setup everything in java, I suggest you look at this question

    Update 2

    If connection to the local database is needed only for developing / debugging purposes I would setup everything using maven profile. Answers from this question will solve that.

    If you need access to the H2 database in production (I can hardly imagine any use-case for that) it's better to do that in spring. Mainly because the application container / environment setup is likely to be different in production (compared to development environment).

    To address the question regarding if to start the server outside of Spring context or not - it all depends on the requirements. One thing you should note is that the server should be started before the datasource is started (otherwise the spring context will not load)

    Update 3

    Unfortunately I'm not able to give you a working solution, but according to the JavaDocs there is a difference between TCP server and Web server. Take a closer look to the JavaDoc of H2 Server class.

    I guess you should use Server.createWebServer() method to create the server (the difference between TCP server and Web server is that

    Another great class you could use org.h2.tools.Console (JavaDoc here) Just run the main method of Console and I guess that should solve everything.

提交回复
热议问题