Using H2 Database with Spring Boot

H2 is one of the more popular embedded databases out there today. Although there are 16-20 embedded databases out in the market, there are only 3 that work well with Spring (H2, Derby and HSQL).
Out of the three, H2 is considered the most matured and supported product. Although not recommended to use in production environment, H2 is robust enough to handle small scale production applications.

Using embedded H2 in Spring Boot is pretty simple. First you add the appropriate connection details in your configuration file, and then you can start using it in Spring like any other SQL database.

You need to add H2 as a maven dependency, there is no installs or setups required!




    driverClassName: org.h2.Driver
    url: jdbc:h2:mem:bootexample;MODE=MySQL

Data Model

Once you have your database setup, you can use it the same way you would use any other database in Spring. You create a model for your database entity

@Table(name = "users")
public class User {
    private Long id;
    private String firstName;
    private String lastName;
    private String password;
    private String email;
    private String phoneNumber;
    private String lastOnline;
    private Boolean enabled;
    public String getLastOnline() {
        return lastOnline;


    public void setLastOnline(String lastOnline) {
        this.lastOnline = lastOnline;

    public Boolean getEnabled() {
        return enabled;

    public void setEnabled(Boolean enabled) {
        this.enabled = enabled;

    public String getEmail() {
        return email;

    public void setEmail(String email) { = email;

    public String getPhoneNumber() {
        return phoneNumber;

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;

    public Long getId() {
        return id;

    public void setId(Long id) { = id;

    public String getFirstName() {
        return firstName;

    public void setFirstName(String firstName) {
        this.firstName = firstName;

    public String getLastName() {
        return lastName;

    public void setLastName(String lastName) {
        this.lastName = lastName;

    public String getPassword() {
        return password;

    public void setPassword(String password) {
        this.password = password;


Finally, you can use Spring’s JpaRepositoryto manipulate your data

package com.fullstacktrace.domain;

import com.fullstacktrace.domain.model.User;

public interface UserRepository extends JpaRepository<User, Integer> {
    public User findByEmail(String email);

Author: Dev

Full Stack Developer at one of the largest Banks in Canada.