How to "allow remote database creation" when using h2 database?

Viewed 7975

I'm trying to create a Spring Boot project with H2 database, which would be accessible by other programs.

application.properties

spring.datasource.url = jdbc:h2:tcp://localhost:8084/~/./db/tech
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.datasource.initialization-mode=always

SpringBootMyApplication.java

@SpringBootApplication
public class SpringBootMyApplication{

    public static void main(String[] args) {
        SpringApplication.run(SpringBootMyApplication.class, args);
    }

    @Bean(initMethod = "start", destroyMethod = "stop")
    public Server h2Server() throws SQLException {
        return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "8084");
    }

}

The exception is:

Caused by: org.h2.jdbc.JdbcSQLNonTransientConnectionException: Database "C:/Users/onz03589/db/tech" not found, either pre-create it or allow remote database creation (not recommended in secure environments) [90149-200]

How to actually "allow remote database creation"?

3 Answers

You need to add "-ifNotExists" parameter to Server.createTcpServer(). But, again, you shouldn't use it together with "-tcpAllowOthers" unless your port is guarded somehow.

You need to add spring boot starter jpa dependency to enable autoconfiguration for h2 database setup.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

I added these two dependencies in the pom.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>


    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.4.200</version>
        <scope>runtime</scope>
    </dependency>

And added below in the Application.properties

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

And it worked for me.

If you have any tables or data to be inserted while creating database. You can do it by putting .sql files under resources directory

enter image description here

Now, you can open your database on http://localhost:port/h2-console

Related