Enabling H2 db in Spring Boot app

Enabling H2 db in Spring Boot app H2 database is an excellent choice for a development process of a Java application. It allows a significant reduction of database administration work and what is probably more important, it makes integration tests creation a lot easier.

h2H2 database is an excellent choice for a development process of a Java application. It allows a significant reduction of database administration work and what is probably more important, it makes integration tests creation a lot easier. You just need to take care of a database structure creation (through Hibernate or an external tool like Liquibase), populate it with some data and the environment is ready for you without worrying about corrupting the database by test data. It is all in memory, so an application restart creates a clean database again. This post describes how to enable H2 database in a Spring Boot application.

H2 database does not start automatically even if Spring Boot is used. It makes sense as not all projects require it. If the particular one will benefit from H2 db, it can be easy added. The below instructions are designed for projects based on Gradle.

Real power of Spring Boot is located in simplicity of adding other components to the project. It is enough to add a proper JAR file to the classpath so Spring Boot notices it and enables the related feature. In this case, I need JPA and H2 libraries so I add two compile entries to the build.gradle file in the dependencies section:

dependencies {
...
compile("org.springframework.boot:spring-boot-starter-data-jpa:1.3.5.RELEASE")
compile("com.h2database:h2:1.4.191")
...
}

When the Gradle project is refreshed, necessary libraries are downloaded.

I add the following application.yml file to the /src/main/resources/ directory:

spring:
profiles:
active: dev
datasource:
dataSourceClassName: org.h2.jdbcx.JdbcDataSource
url: jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1
databaseName:
serverName:
username:
password:
jpa:
database-platform: org.hibernate.dialect.H2Dialect
database: H2
openInView: false
show_sql: true
generate-ddl: true
hibernate:
ddl-auto: create-drop
naming-strategy: org.hibernate.cfg.EJB3NamingStrategy
properties:
hibernate.cache.use_query_cache: false
hibernate.generate_statistics: true

The above code consists of three elements:

  1. Definition of the dev spring profile.
  2. Configuration of a datasource. The Spring Boot application will use it as a main one.
  3. JPA configuration.

That is pretty much all that is needed for H2 to run but I will need H2 console for my convenience during development. The console allows querying H2 as any other relational database using SQL. It should be initiated during the application startup. The following class takes care of it.

package com.dbapresents.myApp.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.embedded.ServletContextInitializer;
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import java.util.Arrays;

@Configuration
public class WebConfiguration implements ServletContextInitializer {
private static final Logger LOGGER = LoggerFactory.getLogger(WebConfiguration.class);

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
initH2Console(servletContext);
}

private void initH2Console(ServletContext servletContext) {
LOGGER.info("Starting H2 console");
ServletRegistration.Dynamic h2ConsoleServlet = servletContext.addServlet("H2Console", new org.h2.server.web.WebServlet());
h2ConsoleServlet.addMapping("/h2console/*");
h2ConsoleServlet.setLoadOnStartup(1);
}
}

On the application startup, the H2 console servlet is loaded and mapped to /h2console/ URL.

When I start the application, I can access the console under this URL: http://localhost:8080/myApp/h2console/.

Do not miss valuable content. You will receive a monthly summary email. You can unsubscribe anytime.

We use cookies

We use cookies on our website. Some of them are essential for the operation of the site, while others help us to improve this site and the user experience (tracking cookies). You can decide for yourself whether you want to allow cookies or not. Please note that if you reject them, you may not be able to use all the functionalities of the site.