H2 database example using hibernate and Spring Boot

Here is a H2 database example using Hibernate and Spring Boot. This example shows you how to create, read, update and delete a record in H2 database. I have used maven to build the project.

h2 database example

Download full source code > H2 example source code (1658)

If you are new to hibernate you can read my Spring Hibernate tutorial.

Introduction to H2 Database

H2 is an open source embedded database built on java ships in a single .jar file. Therefore you can easily embed h2 database into your application. H2 Database has a built in web based console that you can use to interact with the database. You can use H2 database as a in-memory database, embedded database or network database.

You can find more details about H2 Database from H2 Database official website

H2 Database example application

This example application saves request time in a H2 database for each GET request.
h2 example project structure

.pom file

First of all here are the maven dependencies for spring boot to use H2 Database and Hibernate

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"






    <!--create an executable jar-->


Model Class

ApiRequest.java class to store api request data.

@Table(name = "api_request")
public class ApiRequest {
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private Date requestTime;

    public ApiRequest() {

    public ApiRequest(Date requestTime) {
        this.requestTime = requestTime;

    public Long getId() {
        return id;

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

    public Date getRequestTime() {
        return requestTime;

    public void setRequestTime(Date requestTime) {
        this.requestTime = requestTime;

DAO class

ApiRequestDao.java class contains methods for CRUD operations with H2 Database

public class ApiRequestDao {
 private EntityManager entityManager;

 public void create(ApiRequest apiRequest) {

 public void update(ApiRequest apiRequest) {

 public ApiRequest getApiRequestById(long id) {
 return entityManager.find(ApiRequest.class, id);

 public void delete(long id) {
 ApiRequest apiRequest = getApiRequestById(id);
 if (apiRequest != null) {

Service class

ApiRequestService.java acts between DAO and our controller

public class ApiRequestService {

 private ApiRequestDao apiRequestDao;

 public void create(ApiRequest apiRequest) {

Controller class

ApiRequestController.java is the spring web controller which receives the http GET request an process.

public class ApiRequestController {

    private ApiRequestService apiRequestService;

    private static final Logger logger = LoggerFactory.getLogger(ApiRequestController.class);

    @RequestMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map&amp;lt;String, String&amp;gt; getHome() {
        logger.info("Api request received");

        Map&amp;lt;String, String&amp;gt; response = new HashMap&amp;lt;String, String&amp;gt;();
        try {
            ApiRequest apiRequest = new ApiRequest(new Date());
            response.put("status", "success");
        } catch (Exception e) {
            logger.error("Error occurred while trying to process api request", e);
            response.put("status", "fail");

        return response;

Main method

We use main method in WebApplication.java to run the application

public class WebApplication {

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

Property file

application.properties file contains all the required configurations to connect h2 database and run Spring Boot

server.port = 8080

#spring.datasource.url = jdbc:h2:mem:app_db;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.url = jdbc:h2:file:~/h2/app_db;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username = sa
spring.datasource.password =
spring.datasource.driverClassName = org.h2.Driver
spring.jpa.hibernate.ddl-auto = update

H2 Database console

This is an optional step. Add this class if you wish to enable the h2 database console within your app. Once you add this, H2 database console will be available at http://localhost:8080/console.

public class WebConfiguration {
    ServletRegistrationBean h2servletRegistration(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean( new WebServlet());
        return registrationBean;

That’s all. Build the project and run using mvn spring-boot:run command. Visit following url from your browser to record a api call.

Download full source code > H2 example source code (1658)

Enjoyed this article? Share with friends

  • Instead of the optional step where you enable the console, it can easily be done by adding `spring.h2.console.enabled=true` in the application.properties file. No need for extra code

  • Sandesh Dahake

    If i want to use HSQLDB what would be the changes we need . thanks


Subscribe to our email feed and never miss a post

Join Us