Understanding H2 InMemory Database with Spring Boot

Introduction

Basically the database setup involves several steps before we can use it through configured datasource in our application. This actually is required in case of actual project implementations. However, there are situations where we just need a POC to be done for something, and the whole database setup thing still becomes an obligation. Similarly, for unit tests, it would be ideal to have our own set of records in the database, so its independent, without getting impacted by the data changes in the deployed environment. For such use cases, in-memory databases are the ideal solution.

An in-memory database gets created when the application starts, while it gets destroyed when the application stops.

Spring Boot integrates H2 database with lot of ease. So you can easily and quickly switch between a real database and an in-memory database.

Note that, H2 InMemory Database is a relational DBMS written in Java.

Let’s check out a quick demo.


Implementation

Lets generate the Spring Boot project from Spring initializr. Ensure you add Web, JPA, H2 and DevTools dependencies as shown below.

H2 Spring Boot

Let’s look at the generated pom file.

pom.xml

We also notice application.properties file generated as –

application.properties

The property spring.h2.console.enabled=true enables the web console at http://localhost:8080/h2

H2 Web Console

Click on Connect and you get into the page where you see available tables in the DB.

H2 Autogenerated table

You might be wondering, how come Student table got created. The magic happens with data.sql placed at src/main/resources. Just ensure you have the insert statements in the data.sql file as mentioned below –

data.sql

Spring Boot Auto Configuration checks the values in the data.sql file and does the needful for you, i.e. creates the STUDENT table, and executes the insert statements. Smart!

Lets check out how we can operate on these student records.

To do that, let’s have the Student entity class created now.

Student.java

To access the database, let’s write a simple JPA interface which provides the required helper functions to do basic DB operations.

StudentRepository.java

Let’s now customize the Spring Boot entry point class using Command Line Runner, so we will be able to execute our Spring Boot application from command line.

Executing the application

To run the application, you can either do it directly from your Eclipse IDE, or from command-line through below command –

mvn spring-boot:run

When executed, we see the below output displayed on console –

H2 DB Spring Boot application

Download the source code

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.