Spring Boot data with H2 Database

In this tutorial, we’ll learn how to use the H2 in-memory database with Spring Boot. Spring Boot support H2 just like any other database.

H2 is the open-source Java SQL database. Which is mainly used for testing or POC purposes. Spring boot provides out of the box support for H2 and you don’t need to do any special configuration if you want to use the default behavior of H2.

H2 Database Maven Dependencies

In order to use H2 in the Spring Boot application, you need to add below two dependencies. One is for H2 and other for Spring data JPA.

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>

As you can see I didn’t mention the version number here. Because Spring manages the appropriate version number for us. So unless you have any specific requirement, do not provide a version number. This is it, You don’t need to mention anything else in POM or anywhere else.

H2 Database Configuration

Please note these configurations are optional. And He 2 database will work without providing any database configuration at all.

By default Spring Boot tries to connect to “jdbc:h2:mem:testdb” url with username as “sa” and password as “” (EMPTY).

But if you want to change this default behavior, you can do so by providing database configurations as per your need. Below is the configuration from the application.yml.

spring:
  datasource:
    username: hello
    password: jbt
    url: jdbc:h2:mem:jbt_db

Here a new schema (jbt_db) is used instead of the default schema(testdb). Username and password for this new schema will be “hello” and “jbt“.

Spring boot is intelligent enough to understand the Dialect and Driver for H2 database. So you don’t need to provide the same. Unless you want to add some redundant configuration in your application.yml file.

H2 is an In-memory database. It means data will be lost when you stop the server. To have a persistent data store, we should use the file-based storage. To enable the file-based persistence change URL as below.

    url: jdbc:h2:file:/data/h2

Create Schema and populate database

You may want to initialize the database with some tables along with data in these tables before the application is ready. This can be achieved by creating schema.sql and data.sql file.

SCHEMA.SQL : Used to create the table.

DATA.SQL: Used to populate the table created in schema.sql with data.

Leave A Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.