How do you connect to H2 as a remote database instead of embedded mode using Spring Boot?

走远了吗. 提交于 2019-12-06 03:40:53
Kenny Bastani

Make sure that your maven dependencies look like this:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

If you want to use H2 as a remote database using JDBC, you need to make sure that you are already running an H2 database at the specified file path in your connection url.

If you haven't already installed H2, you can get the instructions to run H2 in server mode here: http://www.h2database.com/html/tutorial.html#tutorial_starting_h2_console

Once you have it running, you can connect to it using the same JDBC connection URL you've provided. Just use the following application properties.

spring.datasource.url=jdbc:h2:tcp://localhost/~/stapler
spring.datasource.username=sa
spring.datasource.password=

If you'd rather that the embedded H2 database create your H2 file, that's also possible. Just use the configuration below.

spring.datasource.url=jdbc:h2:file:~/stapler;AUTO_SERVER=true
spring.datasource.username=
spring.datasource.password=

It's possible that the file that is created will be named stapler.mv.db. To tell H2 embedded to use stapler.h2.db instead, you can learn how to do that here: Why is my embedded h2 program writing to a .mv.db file

(Big thanks to Stéphane Nicoll for helping me answer this one)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!