You can install H2 Server as Spring Bean.
First edit pom.xml - remove the <scope>runtime</scope> from the h2 dependency:
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency>
Then add the H2 bean server to the SpringBootApplication or Configuration class:
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean(initMethod = "start", destroyMethod = "stop") public Server h2Server() throws SQLException { return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9092"); } }
Last - edit application.properties - set the database name:
spring.datasource.url=jdbc:h2:mem:dbname spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.jpa.hibernate.ddl-auto=create
Then you can connect to this H2 server from the outside (for example, to your application using H2 DB) using this connection:
jdbc:h2:tcp://localhost:9092/mem:dbname
As a bonus, using this URL you can connect to your application database directly from your IDE .
UPDATE
There is a chance of getting an error message when trying to connect to H2 for Spring boot application version 1.5.x. In this case, just change the version of H2 to the previous one, for example:
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.4.193</version> </dependency>
UPDATE 2
If you need to run several applications with H2 on the same host at the same time, you must install different H2 ports for them in Server.createTcpServer mothod, for example: 9092, 9093, etc.
You can then connect to the H2 DB of these applications with the following URLs:
App1 H2: jdbc:h2:tcp://localhost:9092/mem:dbname App2 H2: jdbc:h2:tcp://localhost:9093/mem:dbname