How to connect to H2 database during development/testing using Spring-Boot

Often times during development we would want to look inside the database to view the schema or data. H2 is a perfect choice for in-memory databases during testing since we do not have to install the database. H2 is instantiated in the same process and data is persisted. While this is convenient, it is difficult to peek inside the database since once the testing is over, the process is killed and the data is lost too.

Spring-boot provides a convenient way to hook up the H2 database. All we need to do is provide the dependency in pom.xml

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

and H2 is available for use.

When not using Dev Tools

In order to look inside the H2 database, we need another dependency spring-boot-starter-web so that Spring instantiates the web server and we can browse the data through the browser. Assuming that you have some data in the database when server starts (import.sql), we need to do following things

Enable web path to access H2 console

In test/resources/application.properties, add the following lines

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

Start Application


mvn -pl persistence spring-boot:run

This will start the application, import data (from import.sql) and start the Tomcat web-server.

Login to the database

On your choice of browser, enter [http://localhost:8080/h2-console](http://localhost:8080/h2-console)
Enter the following for

JDBC URL: jdbc:h2:mem:testdb
User Name: sa
Pasword: <leave this empty>

Connect and you would see a page similar to following

H2 Database Console in Browser

UPDATE: As per response from Stéphane Nicoll, this change is not necessary and I will show you how

When using Dev Tools

Spring-boot provides Spring-boot dev tools, which provides many goodies during the development phase to ease the entire process. To enable dev tools, you need the following dependency in you pom.xml. There is no need to change application.properties file.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>

That’s it. Now start the application

mvn -pl persistence spring-boot:run

Now follow the “Login to the database” section and you would be able to access H2 database.

The codebase is available at Github