DEV Community

Apurv
Apurv

Posted on • Originally published at apurvsheth.Medium on

H2(In-Memory) Database With Spring Boot

  1. Introduction:

In this article, we will learn how to integrate the H2 in-memory database with spring-boot.

As H2 is an in-memory database, it relies on system memory & not disk space to store the data. We use the in-memory database when we do not need to persist the data. Usually, the in-memory databases are volatile, by default, hence data will be lost if an application is restarted.

2. Use Case

It is primarily used for running application test cases by the development team. When changes are made to the codebase, run automated test cases, and when it involves DML operations, H2 Database Engine is used instead of a full-blown database such as PostgreSQL.

3. Tool(s)/Framework(s):

  • Any java project tool suite like Spring tool suit, eclipse, IntelliJ
  • JDK 8 or above
  • Spring-boot

4. Spring-boot & H2 database setup

4.1 Maven Dependencies



com.h2database

h2

runtime

4.2 Configuring H2 DB

Please refer to the below properties(application.yml) to configure H2 DB.


application.yml

From the code snippet of application.yml below, the configuration is almost the same as using any other relational DB. The most important properties are driver class name, database platform & h2 console. please refer to the inline comment for further details.

4 .3 Testing

we can test the H2 database via accessing the “http://localhost:8080/h2-console/" URL. you can enter the username/password which was set during database setup in application.yml &


H2 Database login screen

Once required credentials are entered, you can click on the “Test Connection” to verify H2 DB connectivity.

5. Key takeaways

  • Very easy to use
  • Lightweight and fast.
  • Supports standard SQL and JDBC API.
  • Provides a web console to maintain in the database.
  • Small footprint − ~1.5MB jar file size

GIT repo:

https://github.com/shethaptech/spring-boot/tree/main/h2-service-example

Top comments (0)