How to add H2 database to a Spring Boot project

Disclaimer: The configurations presented here consider the use of Spring JDBC with the H2 Database.

Add the following dependencies to pom.xml.

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

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

Configure the database in application.properties.

By default, Spring Boot configures the application to connect to an in-memory store with the username sa and an empty password.

Baeldung tutorial – “Spring Boot With H2 Database”
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

To test the database, enable the H2 Console, with the following configuration:

spring.h2.console.enabled=true

Start the application and access the H2 Console by navigating to http://localhost:8080/h2-console.

The browser should present the following screen:

H2 Console login screen

Fill the form with the same information provided in application.properties and press “Connect”.

Now you should get the screen bellow:

H2 Console main screen

That’s it.

Notes

For everything to work properly, the H2 dependency has to be included in conjunction with some sort of data access (eg. Spring JDBC or Spring Data JPA). If only the H2 dependency is included the database won’t be created at application startup, and you will get the following error when trying to login to the H2 Console.

References

  1. Baeldung tutorial – Spring Boot With H2 Database
  2. Integrating Spring Boot and Spring JDBC with H2 and Starter JDBC
  3. H2 Database created with spring-boot-starter-data-jpa but not with spring-boot-starter-data-jdbc