Integrating Spring Boot, JPA and H2 Database

View more categories:

1- Objective of Lesson  

H2 is a open source, compact relational database, written in Java language. H2 installer has very little capacity of about 8MB.
One of the interesting features of the  H2 is that you can create an In-Memory Database instead of being stored in a computer hard drive. This makes query speed and manipulation with data very fast. However, if you select the " In-Memory Database" feature, data exists only when the application works, when the application is shut down, the data is also deleted from the memory.
The H2 provides you with an administration tool called  H2 Console, and you work with it through  browser.
In this lesson, I will show you how to create a  Spring Boot project to integrate with the H2 database and use the " In Memory Database" feature, and configure to use the H2 Console administration tool.
There is no many difference if you want to connect to the H2 database, installed on computer (See the appendix at the end of the this post) 

2- Create a Spring Boot project

On the  Eclipse, create the  Spring Boot project:
OK, the project has been created.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""


    <description>Spring Boot + Jpa + H2</description>

        <relativePath/> <!-- lookup parent from repository -->





package org.o7planning.springbooth2;

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

public class SpringBootJpaH2Application {

    public static void main(String[] args) {, args);

3- Entity Class, DAO, DataInit, Controller
package org.o7planning.springbooth2.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Table(name = "PERSON")
public class Person {

    @Column(name = "Id", nullable = false)
    private Long id;

    @Column(name = "Full_Name", length = 64, nullable = false)
    private String fullName;

    @Column(name = "Date_Of_Birth", nullable = false)
    private Date dateOfBirth;

    public Long getId() {
        return id;

    public void setId(Long id) { = id;

    public String getFullName() {
        return fullName;

    public void setFullName(String fullName) {
        this.fullName = fullName;

    public Date getDateOfBirth() {
        return dateOfBirth;

    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;

PersonDAO is an interface extended from  CrudRepository<Person, Long>. Spring Data JPA , which will itself create you a class to implement this interface at the time of starting the application.
See also:
  • TODO Link!
package org.o7planning.springbooth2.dao;

import java.util.Date;
import java.util.List;

import org.o7planning.springbooth2.entity.Person;
import org.springframework.stereotype.Repository;

public interface PersonDAO extends CrudRepository<Person, Long> {

    public List<Person> findByFullNameLike(String name);

    public List<Person> findByDateOfBirthGreaterThan(Date date);

The  DataInit implements  ApplicationRunner  interface. It will automatically run at the time when the application starts. In this class, we will insert some records to the  PERSON ​​​​​​​table.
package org.o7planning.springbooth2.init;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.o7planning.springbooth2.dao.PersonDAO;
import org.o7planning.springbooth2.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

public class DataInit implements ApplicationRunner {

    private PersonDAO personDAO;

    private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

    public DataInit(PersonDAO personDAO) {
        this.personDAO = personDAO;

    public void run(ApplicationArguments args) throws Exception {
        long count = personDAO.count();

        if (count == 0) {
            Person p1 = new Person();


            Date d1 = df.parse("1980-12-20");
            Person p2 = new Person();

            Date d2 = df.parse("1985-11-11");


package org.o7planning.springbooth2.controller;

import org.o7planning.springbooth2.dao.PersonDAO;
import org.o7planning.springbooth2.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

public class MainController {

    private PersonDAO personDAO;

    public String index() {
        Iterable<Person> all = personDAO.findAll();

        StringBuilder sb = new StringBuilder();

        all.forEach(p -> sb.append(p.getFullName() + "<br>"));

        return sb.toString();


4- Configure Spring Boot & H2

In this example, I will configure the  Spring Boot to use the  H2 as an In-memory Database, which means we don't need to install the H2 database. It will automatically be created and stored in computer memory.
Trong một trường hợp khác, nếu bạn đã cài đặt sẵn một cơ sở dữ liệu H2 trên máy tính của bạn, và muốn tương tác ứng dụng Spring Boot với cơ sở dữ liệu  này, bạn có thể xem thêm phụ lục ở phía cuối bài viết này.
# To See H2 Console in Browser:
# http://localhost:8080/h2-console
# Enabling H2 Console

# ===============================
# DB
# ===============================


# ===============================
# ===============================


This configuration tells the Spring to start the administration tool of the H2 database and you can access this tool on the browser:


This configuration tells  Spring that you want to use the In-Memory H2 Database.


This structure tells the  Spring to create (or update) the structure of structure-based table of  Entity classes. Thus, the PERSON table will automatically be created by the structure of the Person class. 

5- Run the application

On the  Eclipse, run your application:
At this moment, the  H2 Console is also started with the application and you can access this administration tool:
The  PERSON table has automatically been created based on the structure of the  Person class.
Query the  PERSON ​​​​​​​table:

6- Appendix H2

  • TODO

View more categories: