[JAVA] Implement REST API with Spring Boot and JPA (Application Layer)

Implementing a simple Web REST API server with Spring Boot + MySQL --Qiita

Outline Implement the application layer according to the following design. Implementing a simple Web REST API server with Spring Boot + MySQL --Qiita

Implement the following 2 classes.

├── application
│   ├── controller
│   │   └── UserController.java
│   └── resource
│       └── UserBody.java

UserBody.java A class that maps the body at the time of a POST request for user registration. It has validation and conversion process to domain object.

UserBody.java


package com.example.springapi.application.resource;

import com.example.springapi.domain.object.User;
import lombok.Data;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

/**
 *Request body mapping class
 */
@Data
public class UserBody {

    @NotBlank
    @Size(max = 18)
    private String id;

    @NotBlank
    private String value;

    /**
     *Convert to domain object
     *
     * @return domain object
     */
    public User toDomainUser() {
        return User.builder()
                .id(this.id)
                .value(this.value)
                .build();
    }
}

UserController.java

UserController.java


package com.example.springapi.application.controller;

import com.example.springapi.application.exception.NotFoundException;
import com.example.springapi.application.resource.ErrorResponse;
import com.example.springapi.application.resource.UserBody;
import com.example.springapi.domain.object.User;
import com.example.springapi.domain.service.UserService;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 *User-operated controller
 */
@RestController
@RequiredArgsConstructor
@RequestMapping(path = "/v1/users")
public class UserController {

    @NonNull
    private final UserService userService;

    /**
     *User search
     *
     * @param id User ID you want to search
     * @return user
     */
    @GetMapping("{id}")
    @ResponseStatus(HttpStatus.OK)
    public User findById(@PathVariable("id") String id) {
        return this.userService.findById(id).orElseThrow(RuntimeException::new);
    }

    /**
     *User created and updated
     *
     * @param userBody Request body
     * @return User after update
     */
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public User save(@RequestBody @Validated UserBody userBody) {
        return this.userService.save(userBody.toDomainUser());
    }

    /**
     *Delete user
     *
     * @param id User ID you want to delete
     */
    @DeleteMapping("{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteById(@PathVariable("id") String id) {
            this.userService.deleteById(id);
    }
}

* Annotations used

@RestController Extended annotation of @Controller. @Controller is an alias for @Compornent, like @Service and @Repository. In addition, @RestController assigns @ResponseBody to each method.

@ResponseBody By giving it to the method, the java object of the return value is converted to json.

@RequestMapping Annotation that maps the path specified in the argument path to the method in the Http method specified in the argument method. By assigning it to the class, the argument path becomes the base path of the method belonging to the class.

@***Mappring Extended annotation of @RequestMapping. Annotation that can omit method.

@ResponseStatus Annotation that can specify the status code.

@PathVariable Annotation that maps path parameters to arguments.

@RequestBody Annotation that maps the body of the request to the argument.

@Validated Annotation that enables the validation annotation given to the mapped class by giving it at the same time as @RequestBody.

Recommended Posts

Implement REST API with Spring Boot and JPA (Application Layer)
Implement REST API with Spring Boot and JPA (Infrastructure layer)
Implement REST API with Spring Boot and JPA (domain layer)
Implement a simple Rest API with Spring Security with Spring Boot 2.0
Implement REST API in Spring Boot
Implement a simple Rest API with Spring Security & JWT with Spring Boot 2.0
Implement a simple Web REST API server with Spring Boot + MySQL
[Beginner] Let's write REST API of Todo application with Spring Boot
Hello World (REST API) with Apache Camel + Spring Boot 2
[Spring Boot] Get user information with Rest API (beginner)
Customize REST API error response with Spring Boot (Part 2)
Customize REST API error response with Spring Boot (Part 1)
Spring with Kotorin --4 REST API design
Handle Java 8 date and time API with Thymeleaf with Spring Boot
Inquiry application creation with Spring Boot
Connect to database with spring boot + spring jpa and CRUD operation
Implement Spring Boot application in Gradle
Creating REST APIs with Spring JPA Data with REST and Lombok incredibly easy.
Processing at application startup with Spring Boot
HTTPS with Spring Boot and Let's Encrypt
Start web application development with Spring Boot
Launch Nginx + Spring Boot application with docker-compose
Implement CRUD with Spring Boot + Thymeleaf + MySQL
Implement paging function with Spring Boot + Thymeleaf
Run WEB application with Spring Boot + Thymeleaf
Implementation method for multi-data source with Spring boot (Mybatis and Spring Data JPA)
Configure Spring Boot application with maven multi module
Try to implement login function with Spring Boot
Create a web api server with spring boot
Spring Boot 2.3 Application Availability
Download with Spring Boot
Spring Boot application built-in Tomcat, Apache and WebSocket integration
Try using DI container with Laravel and Spring Boot
Switch environment with Spring Boot application.properties and @Profile annotation
Automatically map DTOs to entities with Spring Boot API
Try using OpenID Connect with Keycloak (Spring Boot application)
Spring Security usage memo: Cooperation with Spring MVC and Boot
Spring Boot with Spring Security Filter settings and addictive points
A memorandum when creating a REST service with Spring Boot
Introduce swagger-ui to REST API implemented in Spring Boot
Attempt to SSR Vue.js with Spring Boot and GraalJS
Connect Spring Boot and Angular type-safely with OpenAPI Generator
CSRF countermeasure policy and implementation example in REST application using "Spring Boot" + "EXT JS"
Generate barcode with Spring Boot
Hello World with Spring Boot
Spring with Kotorin --8 Repository layer
Spring Boot Introductory Guide I tried [Accessing Data with JPA]
Get started with Spring boot
Hello World with Spring Boot!
[Spring Boot] Web application creation
Run LIFF with Spring Boot
SNS login with Spring Boot
File upload with Spring Boot
Spring Boot starting with copy
Let's make a simple API with EC2 + RDS + Spring boot ①
Until INSERT and SELECT to Postgres with Spring boot and thymeleaf
How to call and use API in Java (Spring Boot)
Spring with Kotorin ―― 7. Service layer
Try hitting the zip code search API with Spring Boot
CICS-Run Java application-(4) Spring Boot application
Spring Boot starting with Docker