Create a CRUD RESTFul Web Service with Spring Boot and data stored in H2 in-memory database accessed via JPA.

Building a RESTful Web Service with Spring Boot

Create a CRUD RESTFul Web Service with Spring Boot and data stored in H2 in-memory database accessed via JPA.

Mar 15, 2019

  • Java
  • Spring Boot
  • JPA

  • Introduction

    Let’s create a CRUD REST API with Spring Boot, JPA, and H2.

    • Getting Started.
    • Create an Entity Class.
    • Create the JPA Data Repository Layer.
    • Create the Rest Controller.
    • Create Unit Testing.
    • Build and run the Project.

    What you’ll need

    • A favourite text editor or IDE
    • JDK 1.8 or later
    • Maven 3.2+

    Overview

    We will create an Account Resource for MyBank exposing services below:

    • Get all Accounts - @GetMapping(“/accounts/all”)
    • Get Account with specified id - @GetMapping(“/accounts/{id}”)
    • Create a new Account - @PostMapping(“/accounts/new”)
    • Update Account with amount parameter - @PutMapping(“/accounts/{id}”)
    • Delete Account with specified id - @DeleteMapping(“/accounts/{id}”)

    When Designing RESTful APIs, the following HTTP methods should be considered:

    • GET: Should be used to retrieve elements
    • POST: Should be used to create new resources
    • PUT: Should be used to update a known resource.
    • DELETE: Used to delete a resource.

    Project Structure

    Following is the directory structure of our application

    Getting Started

    Create a new Maven project using your favourite IDE an import the pom.xml below. This will have all the dependencies required for the project. You can also use Spring Initializr http://start.spring.io/ that is an excellent tool to bootstrap your Spring Boot projects.

    Spring Boot Application

    Create a new file App.java in the root package of your application. This is the main entry point of the Spring Boot application.

    Entity

    Now, let’s create the Account model with the following fields:

    • id: Primary Key with Auto Increment.
    • name: Name of the account holder
    • balance: balance of the account

    Create a package model and a new file Account.java

    All domain models must be annotated with @Entity annotation. It is used to mark the class as a persistent Java class.

    • @Table annotation is used to provide the details of the table that this entity will be mapped to.
    • @Id annotation is used to define the primary key.
    • @GeneratedValue annotation is used to define the primary key generation strategy. In the above case, we have declared the primary key to be an Auto Increment field.

    Spring Boot Auto Configuration detects that we are using an in-memory database H2. It auto-configures the property to create the database tables based on the Entities.

    JPA Data Repository Layer

    Next, let’s create the repository. For this example, we will use a simple in-memory database H2. Create a package repository and a new file AccountRepository.java

    The @Repository annotation tells Spring to bootstrap the repository during the component scan.You will now be able to use JpaRepository’s methods like save(), findOne(), findAll(), count(), delete() etc. You don’t need to implement these methods. They are already implemented by Spring Data JPA’s SimpleJpaRepository. This implementation is plugged in by Spring automatically at runtime.

    Let’s add some initial data for testing. Create a file data.sql in the folder /src/main/resources/

    Exception

    Create a package exception and a new file ResourceNotFoundException.java

    The @ResponseStatus annotation will cause Spring boot to respond with the specified HTTP status code whenever this exception is thrown from your controller.

    Rest Controller

    Create a package controller and a new file AccountController.java

    @Autowired is used so that we can retrieve and save data to the database.

    Rest Controller

    • The @RestController annotation is used to define the RESTful web services. It serves JSON, XML and custom response. Request Mapping
    • The @RequestMapping annotation is used to define the Request URI to access the REST Endpoints. We can define Request method to consume and produce the object. Request Body
    • The @RequestBody annotation is used to define the request body content type. Path Variable
    • The @PathVariable annotation is used to define the custom or dynamic request URI. The Path variable in request URI is defined as curly braces {} Request Parameter
    • The @RequestParam annotation is used to read the request parameters from the Request URL. By default, it is a required parameter.

    Unit Testing

    Create the unit testing file MyBankAppTests.java

    Build and Run the application

    $ mvn spring-boot:run

    You can test your endpoints going to:

    • http://localhost:8080/accounts/all
    • http://localhost:8080/accounts/1

    To test PUT, POST and DELETE operations, I recommend using postman that can be downloaded here

    Congratulations!! :trophy: