Spring Boot H2 Database Example with Hibernate

Spring Boot H2 Database Example with Hibernate thumbnail
By Dhiraj 19 March, 2017

This tutorial explains about using H2 database in spring boot application with hibernate as a JPA provider. We will also take a look into accessing H2 db console in spring boot along with spring security integration.Here we will be creating a spring boot H2 database example app which will have REST endpoints exposed and perform some db operations.

Why H2 database and Spring Boot

Using H2 database is fast, open source and provides JDBC API to connect to java applications. It is very convenient to use and provides browser based console. H2 database is mostly used as in-memory database and Spring boot provides out of the box support for H2. Spring Boot can auto-configure embedded H2 database meaning you dont need to provide any H2 specific configurations in your spring boot application. Include the required dependencies and spring boot will take care of other things.

The example shown here is primarily meant to use H2 database during development phase as it is light, fast and easy to use and provides convenient way to emulate other DBs which we use in production environment.

H2 and spring boot Maven Dependencies

Since we want to have a H2 console, the scope is not defined as runtime and hence by default it is compile time.

spring-boot-starter-parent: It provides useful Maven defaults. It also provides a dependency-management section so that you can omit version tags for existing dependencies.

spring-boot-starter-web: It includes all the dependencies required to create a web app. This will avoid lining up different spring common project versions.

spring-boot-starter-tomcat: It enable an embedded Apache Tomcat 7 instance, by default.This can be also marked as provided if you wish to deploy the war to any other standalone tomcat.

spring-boot-starter-data-jpa: It provides key dependencies for Hibernate, Spring Data JPA and Spring ORM.


Defining Spring Boot Application class

@SpringBootApplication enables many defaults.It is a convenience annotation that adds @Configuration, @EnableAutoConfiguration, @EnableWebMvc, @ComponentScan

The main() method uses Spring Boot SpringApplication.run() method to launch an application.

package com.devglan;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);


 Other Interesting Posts
Spring Data JPA Example
Spring Boot Hibernate 5 Example
Spring Boot Actuator Complete Guide
Spring Boot Actuator Rest Endpoints Example
Spring 5 Features and Enhancements
Spring Boot Thymeleaf Example
Securing REST API with Spring Boot Security Basic Authentication
Spring Boot Security Password Encoding using Bcrypt Encoder
Websocket spring Boot Integration Without STOMP with complete JavaConfig

H2 database configuration in Spring Boot

The important thing to note here is the url.DB_CLOSE_ON_EXIT=FALSE disables the database automatic shutdown and Spring Boot will ensure to close it once access to the database is no longer needed.


Hibernate Entity Class

Following is the entity class. The class is annotated as hibernate entity.

package com.devglan.model;

public class UserDetails {
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;
	private String firstName;
	private String lastName;
	private String email;
	private String password;
	//getters and setters goes here

Defining Spring Boot Controller

Let us define our controller. It has one url mapping that intercepts request at /list and returns all users present in db.

package com.devglan.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.devglan.model.UserDetails;
import com.devglan.service.UserService;

public class UserController {
	private UserService userService;
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ResponseEntity> userDetails() {
		List userDetails = userService.getUserDetails();
		return new ResponseEntity>(userDetails, HttpStatus.OK);


Defining Service Class

package com.devglan.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.devglan.dao.UserDao;
import com.devglan.model.UserDetails;
import com.devglan.service.UserService;

public class UserServiceImpl implements UserService {

	private UserDao userDao;

	public List getUserDetails() {
		return userDao.getUserDetails();


Defining Dao Implementation

Let us define the dao. Here we are free to choose JPA entitymanager to perform db operations or use hibernate session as shown below:

package com.devglan.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.devglan.dao.UserDao;
import com.devglan.model.UserDetails;

public class UserDaoImpl implements UserDao {

    private EntityManager entityManager;
	public List getUserDetails() {
		Criteria criteria = entityManager.unwrap(Session.class).createCriteria(UserDetails.class);
		return criteria.list();


H2 database Console Configuration

Following is the configuration to view the H2 database console in the path /console. It declares the servlet wrapper for the H2 database console /console. Here we have imported WebServlet class that is from H2.

package com.devglan;

import org.h2.server.web.WebServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

public class BeanConfig {

    ServletRegistrationBean h2servletRegistration(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new WebServlet());
        return registrationBean;



Following are some sample DML. We will be creating some dummy user details using following insert statements.

create table User_Details (id integer not null auto_increment, email varchar(255), first_Name varchar(255), last_Name varchar(255), password varchar(255), primary key (id));

INSERT INTO user_details(email,first_Name,last_Name,password) VALUES ('admin@admin.com','admin','admin','admin');

INSERT INTO user_details(email,first_Name,last_Name,password) VALUES ('john@gmail.com','john','doe','johndoe');

INSERT INTO user_details(email,first_Name,last_Name,password) VALUES ('sham@yahoo.com','sham','tis','shamtis');

Accessing H2 Database Console

Hit the url - localhost:8080/console and you can see folowing screen.


Click on connect button and you will be forwarded to /console page

Now run above sqls

And try to access localhost:8080/list and you will see below screen.


Adding Spring Security to H2 Datbase Console

Add following maven dependencies to the pom file. Once this dependency is added, Spring Boot will not allow the access of /console without default basic authentication.

One thing you can do is use default username/password provided by spring boot security to access the /console page. The default username is user and default password is logged by spring boot in the console.


You can also define your custom security configurations or remove the authentication for /console as below:

package com.devglan;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

public class SecurityConfig extends WebSecurityConfigurerAdapter {

	protected void configure(HttpSecurity httpSecurity) throws Exception {


I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Download source


If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.

Further Reading on Spring Boot