Spring Boot Web MVC Using Embedded H2 Database Example

In this example, we will show you how to develop a spring boot web application using spring web mvc, spring data jpa, spring thymeleaf template engine and h2 embdded database library jars. This web application provide add employee and list added employees function. Please see the function demo in below video.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/CXeykzM9jtI

1. Create Spring Boot Web Application.

First we should create a spring boot web application using spring tool suite New Spring Starter Project wizard. You can refer article Spring Boot Hello World Example In STS. Input related project information like below picture.

spring boot web mvc starter project

Select JPA, H2, Thymeleaf and Web dependencies library in the following New Spring Starter Project Dependencies wizard panel.

You can use spring data jpa library to operate embedded h2 database table data flexible, the h2 jdbc driver classes is provided in h2 library. The thymeleaf library provide template engine which is used to render html web page. And the spring web library is used to construct application web mvc structure.

spring boot web mvc required library

Click Finish button to complete the spring boot starter project create process.

2. Spring Boot Web Application Project Files Structure.

Below is the example project panel, it contiains below source files.

spring web mvc h2 database example source files

  1. SpringBootWebMvcApplication.java : Spring boot application main class.
  2. ConstantVariable.java : Save constant variables used in this example.
  3. CustomErrorController.java : This class is used to define custom error page to display to client user when there are error occured. Please refer How To Disable Or Customize Spring Boot Whitelabel Error Page.
  4. EmployeeController.java : This is the main controller in this example, it provide three function mapping to different request url, the three functions provide display add employee form page, add employee and list employees feature.
  5. Employee.java : This is the entity java bean that present one employee infoormation, it map to h2 database EMPLOYEE table.
  6. EmployeeRepository.java : This is an interface that extends org.springframework.data.jpa.repository.JpaRepository, the JpaRepository interface has encapsulated all basic db operations ( insert, update, select  and delete ) for you, you can use it directly to operate table data without coding sql command.
  7. addEmployee.html : Display the add employee form page, user can input employee info in this page and click submit button to add one employee.
  8. listEmployee.html : List added employees info in a table.
  9. application.properties : This is the example configuration file, contains h2 database related datasource jdbc connection information.
  10. pom.xml : The maven dependencies definition xml file. Define example used libraries.

3. Spring Boot Web MVC Example Source Files.

3.1 SpringBootWebMvcApplication.java

package com.dev2qa.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/* @SpringBootApplication consists of @Configuration, @ComponentScan and @EnableAutoConfiguration.
 * This annotation enable component scan and auto configuration. */


@ComponentScan(basePackages = {"com.dev2qa.example"})
public class SpringBootWebMvcApplication {

    public static void main(String[] args) {
      /* Responsible for launching the boot application. */
        SpringApplication.run(SpringBootWebMvcApplication.class, args);

3.2 ConstantVariable.java

package com.dev2qa.example.constant;

public class ConstantVariable {

    public static String EMPLOYEE_LIST = "employees";


3.3 CustomErrorController.java

You can find the source code of this java file in article How To Disable Or Customize Spring Boot Whitelabel Error Page.

3.4 EmployeeController.java

package com.dev2qa.example.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.dev2qa.example.constant.ConstantVariable;
import com.dev2qa.example.model.Employee;
import com.dev2qa.example.repository.EmployeeRepository;

public class EmployeeController {

    private EmployeeRepository employeeRepository;

    /* List added employees. */
    @RequestMapping(value="/listEmployee", method=RequestMethod.GET)
    public String listEmployeeList(Model model) {
        List<Employee> employeeList = this.employeeRepository.findAll();

        model.addAttribute(ConstantVariable.EMPLOYEE_LIST, employeeList);

        return "listEmployee";

    /* Display add employee form page. */
    @RequestMapping(value="/addEmployeePage", method=RequestMethod.GET)
    public String addEmployeePage() {
        return "addEmployee";

    /* Add user submitted employee info to h2 databae and redirect to list employees page. */
    @RequestMapping(value="/addEmployee", method=RequestMethod.POST)
    public String addEmployee(Employee employee) {
        return "redirect:/employee/listEmployee";

3.5 Employee.java

package com.dev2qa.example.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/* Annotate Employee class as JPA Entity class. 
 * Because do not specify the entity table name 
 * then use EMPLOYEE as the table name by default. */
public class Employee {

    /* Identify id as this entity's unique identifier. The id value is auto generated. */
    private Long id;

    private String userName;

    private String password;

    private String email;

    private String sex;

    private long age;

    private String title;

    private long salary;

    public Long getId() {
        return id;

    public void setId(Long id) {
        this.id = id;

    public String getUserName() {
        return userName;

    public void setUserName(String userName) {
        this.userName = userName;

    public String getPassword() {
        return password;

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

    public String getEmail() {
        return email;

    public void setEmail(String email) {
        this.email = email;

    public String getSex() {
        return sex;

    public void setSex(String sex) {
        this.sex = sex;

    public long getAge() {
        return age;

    public void setAge(long age) {
        this.age = age;

    public String getTitle() {
        return title;

    public void setTitle(String title) {
        this.title = title;

    public long getSalary() {
        return salary;

    public void setSalary(long salary) {
        this.salary = salary;

3.6 EmployeeRepository.java

package com.dev2qa.example.repository;

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.dev2qa.example.model.Employee;

/* Extends JpaRepository which has provide all basic crud methods to entiry Employee table. */
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    /* We add a custom method here but do not use it in this example. 
     * The method name must follow findBy<column name> pattern, then JpaRepository
     * will implement the detail jdbc query code which we do not need to care, we just 
     * need to call this method and pass in the userName to get result list. 
     * */
    List<Employee> findByUserName(String userName);

3.7 addEmployee.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
        <meta charset="UTF-8">
        <title>Add Employee</title>
        <h2>Add Employee </h2>

        <form method="post" action="/employee/addEmployee">
            <table border=0 >
            <tr><td align="right">User Name:</td><td align="left"><input type="text" name="userName" size="50"></input></td></tr>
            <tr><td align="right">Password:</td><td align="left"><input type="password" name="password" size="50"></input></td></tr>
            <tr><td align="right">Email:</td><td align="left"><input type="text" name="email" size="50"></input></td></tr>
            <tr><td align="right">Title:</td><td align="left"><input type="text" name="title" size="50"></input></td></tr>
            <tr><td align="right">Sex:</td><td align="left"><input type="radio" name="sex" value="male"> Male<input type="radio" name="sex" value="female"> Female</td></tr>
            <tr><td align="right">Salary:</td><td align="left"><input type="text" name="salary" size="50"></input></td></tr>
            <tr><td align="right">Age:</td><td align="left"><input type="text" name="age" size="50"></input></td></tr>
            <tr><td align="right"></td><td align="left"><input type="submit"></input></td></tr>


3.8 listEmployee.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
        <meta charset="UTF-8">
        <title>List Employee</title>
        <h2>Employee List</h2>

        <a th:href="@{'/employee/addEmployeePage'}">Add Employee</a>


        <table th:if="${ not #lists.isEmpty(employees) }" border=1>
            <td>User Name</td>
        <tr th:each="employee : ${employees}">
            <td th:text="${employee.userName}"></td>
            <td th:text="${employee.password}"></td>
            <td th:text="${employee.email}"></td>
            <td th:text="${employee.title}"></td>
            <td th:text="${employee.sex}"></td>
            <td th:text="${employee.salary}"></td>
            <td th:text="${employee.age}"></td>


3.9 application.properties


# Enable h2 database console.

# Define h2 database jdbc connection parameter values.
# When example start, you can access the embedded h2 database with below parameter values to see the EMPLOYEE table.

When you run the example application, you can access h2 db console in a web browser with url http://localhost:8080/h2-console/. Then input h2 database related jdbc parameter value in the page like below.

spring boot web application embedded h2 database jdbc connection console page

When you click the Connect button, you can find EMPLOYEE table in the web page like below.

spring web mvc application used embedded h2 database employee table

3.10 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">


    <description>Spring Boot Web MVC Example.</description>

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






  1. H2 Database Tutorial
  2. Spring Boot Resolve Whitelabel Error Page Example
0 0 votes
Article Rating
Notify of

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

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x