by BehindJava

What is H2 In-Memory database and how to configure it in a Spring Boot application

Home » springboot » What is H2 In-Memory database and how to configure it in a Spring Boot application

In this tutorial we are going to learn about H2 In-Memory database and its configuration in Spring Boot in detail which is very easy to setup and easy to use.

H2 is an open-source lightweight Java database. It can be embedded in Java applications or run in the client-server mode. H2 database can be configured to run as in-memory database, which means that data will not persist on the disk.

When to use it?

  • While writing new code and debugging to check the flow of code
  • Testing code

And the good thing is that with an In-Memory database its absolutely safe to play and experiment with your data and code. Insertions and deletions can be done many a times since it doesn’t affect the standalone MySQL server.

All the test data you insert to your In-Memory database stays in the memory and it is cleared once we stop or restart the Spring Boot application.

Since it is easy to configure, I will be using H2 In-Memory database in further tutorials and here we are going to configure H2 In-Memory database in our UserMicroservice project.

Firstly, we need to add H2 In-Memory database dependency that is available in Maven Central Repository to your pom.xml as mentioned below.

<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.200</version>
    <scope>test</scope>
</dependency>

Under src/main/resources in the application.properties of UserMicroservie add the following properties as shown below.

The purpose of adding spring.h2.console.enabled=true is to enable the h2 console so that we can open browser window and sign in with username and password and be able to browse through the database structure and run SQL requests.

H2 database server has a little firewall built in, since we are connecting UsersMicroservice through API Gateway. We will need to enable connections from other addresses by adding the following property i.e. spring.h2.console.settings.web-allow-others=true.

Properties:

spring.h2.console.settings.web-allow-others=true
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb  
spring.datasource.driverClassName=org.h2.Driver  
spring.datasource.username=sa  
springspring.datasource.password=  
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect  

Now start as Spring boot application app in the following order i.e., Eureka server, Spring Cloud API Gateway and UserMircroservice. Once all the applications are started successfully, we are going to access the H2 console through the API Gateway.