Spring Boot and H2 in memory database – why, what and how ?

Frequently asked questions about Spring Boot, JPA, Hibernate and H2

Q: How does H2 and Spring Boot combination work ?

Spring Boot is intelligent – if an application is dealing with in memory db (like H2), it looks at the entities (classes annotated with @Entity) and creates the database and tables. However, if developer connects to a mysql\postgresql\oracle etc database, Spring Boot knows that it is a permanent database.

Q: How does Spring Boot Application connect to the database H2 ?

It is down to Spring Boot Auto Configuration! As soon as Spring Boot sees H2 in the classpath, it auto configurates a data source based on settings in properties file. Below is an example :

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa

Note that parameters names follow certain rules – they have to be named exactly as it is shown below. Otherwise Spring Boot uses default values. They are :

  • spring.datasource.driver-class-name=org.h2.Driver

  • spring.datasource.url=jdbc:h2:mem:testdb

  • spring.datasource.username=sa

  • spring.datasource.password=

Thus, as it was mentioned above, just adding the H2 runtime jar into dependencies section of Maven project is sufficient.

Q: What happens if H2 is not in the classpath ?

The following error occurs : Failed to configure a DataSource … Consider the following: If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.

Q: Why is the data lost between restart ?

H2 is an in memory database, it is not a persisted database.

Error: H2 console is not launched up ?

It must be enabled in application.properties :

spring.h2.console.enabled=true

Previous

Leave a Reply

Your email address will not be published. Required fields are marked *