Spring Boot + Spring Data JPA + H2 Database

In this example , we will create a simple Spring boot application which will interact with the H2 database using Spring JPA library.

H2 database is an in memory database .For this tutorial , we will use H2 database for this demo so that we don’t need to perform heavy installation for other database like Oracle,MySQL.

GitHub Link

Tools –

  • Spring Boot
  • Spring JPA
  • H2 Database
  • IntelliJ IDEA editor
  • Maven
  • Lombok

Step 1: Create the simple spring boot web application in IntelliJ IDEA editor

Our final Project structure will look like below–

Step 2: Now define all maven dependencies required in this project

<?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">
<modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.myjavablog</groupId>
<artifactId>springhibernatewithh2database</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springhibernatewithh2database</name>
<description>Demo project for Spring Boot</description>
<pre><code><properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <!--<scope>runtime</scope>-->
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build></code></pre>
</project>

  • Lombok – We will be using lombok third party library to reduce boilerplate code for model/data objects, e.g., it can generate getters and setters for those object automatically by using Lombok annotations. The easiest way is to use the @Data annotation.
  • spring-boot-starter-data-jpa – This jar is used to connect to database .It also has a support to provide different JPA implementations to interact with the database like Hibernate, JPA Repository, CRUD Repository etc.
  • h2 – Its used to create H2 database when the spring boot application boots up. Spring boot will read the database configuration from application.properties file and creates a DataSource out of it.

Step 2: Create the Model class

package com.myjavablog.pojo;

import javax.persistence.*;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table
public class UserDetails {
<pre><code>@Id
@Column
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column
private String firstName;
@Column
private String lastName;
@Column
private String email;
@Column
private String password;</code></pre>
}

We have used Lombok library in Model class . You can see below annotation which are coming from Lambok jar –

  • @Data – Define this class as Model class
  • @Builder – To build the model object at runtime ex. Create mock object for unit testing
  • @AllArgsConstructor – Create constructor with all arguments
  • @NoArgsConstructor – Default constructor

So Lombok takes care of everything for you right from creating setters/ getters, Constructor , Build runtime objects and avoids boilerplate code .

Step 3: Configuration for the H2 database bean

package com.myjavablog.config;

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;

@Configuration
public class BeanConfig {
<pre><code>@Bean
ServletRegistrationBean h2servletRegistration() {
    ServletRegistrationBean registrationBean = new ServletRegistrationBean(new WebServlet());
    registrationBean.addUrlMappings("/console/*");
    return registrationBean;
}</code></pre>
}

We can also configure the security for the application.

package com.myjavablog.config;

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

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
<pre><code>@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf().disable().authorizeRequests().antMatchers("/").permitAll().and().authorizeRequests()
            .antMatchers("/console/**").permitAll()
            .antMatchers("/list/**").permitAll();
    httpSecurity.headers().frameOptions().disable();
}</code></pre>
}

Step 4: Service layer

package com.myjavablog.service;

import com.myjavablog.pojo.UserDetails;

import java.util.List;

public interface UserService {
public List getUserDetails();
}

package com.myjavablog.service;

import com.myjavablog.dao.UserDao;
import com.myjavablog.pojo.UserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
<pre><code>@Autowired
UserDao userDao;

@Override
public List getUserDetails() {

    return userDao.getUserDetails();
}
}

Step 5: DAO layer

package com.myjavablog.dao;

import com.myjavablog.pojo.UserDetails;

import java.util.List;

public interface UserDao {
<pre><code>public List getUserDetails();
}

package com.myjavablog.dao;

import com.myjavablog.pojo.UserDetails;

import javax.persistence.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public class UserDaoImpl implements UserDao {
@PersistenceContext
private EntityManager entityManager ;

@Override
public List getUserDetails() {
    Criteria criteria;
    criteria = entityManager.unwrap(Session.class).createCriteria(UserDetails.class);
    return criteria.list();
}
}

Step 7: Create Controller class

package com.myjavablog.controller;

import com.myjavablog.pojo.UserDetails;
import com.myjavablog.service.UserService;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@Controller
public class UserController {
@Autowired
private UserService userService;

@RequestMapping(value = "/list", method = RequestMethod.GET)
public ResponseEntity userDetails() {

    List userDetails = userService.getUserDetails();
    return new ResponseEntity(userDetails, HttpStatus.OK);
}
}

Step 8 : Create a properties file to configure Spring boot application and database

spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
server.port=8081
server.error.whitelabel.enabled=false

Step 9: Now application is ready . Run the application and Java application and access URL http://localhost:8081/console to access H2 database.

Once you connect to it you can insert records to table.

Now you can access the application to get the list of users.

Leave a Comment

Bitnami