Implement REST API with Spring Boot and JPA (Infrastructure layer)

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

Outline Implement the infrastructure layer according to the following design. Consider the architecture of Web API implemented by Spring Boot --Qiita

Create the following 3 classes.

├── infrastructure
│   ├── entity
│   │   └── UserEntity.java
│   └── repository
│       ├── UserJpaRepository.java
│       └── UserRepositoryImpl.java

UserEntity.java The class to which MySQL records are mapped. Define a method to convert bidirectionally with Domain Object (User.java).

UserEntity.java


package com.example.springapi.infrastructure.entity;

import com.example.springapi.domain.object.User;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 *RDB record mapping class
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "test_users")
public class UserEntity {
    @Id
    @Column(name = "id")
    private String id;

    @Column(name = "value")
    private String value;

    /**
     *Create an instance from a domain object
     *
     * @param user domain object
     * @return UserEntity
     */
    public static UserEntity build(User user) {
        return UserEntity.builder()
                .id(user.getId())
                .value(user.getValue())
                .build();
    }

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

* JPA annotation

@Entity This expresses the JPA Entity (mapped class). @Table Specify the table name. @id Specifies that it is a primary key. In the case of a compound key, the writing method changes. @Column Specify the column name of the table.

* Lombok annotation

@NoArgsConstructor Automatically create a constructor with no arguments. A constructor with no arguments is required due to the life cycle of JPA Entity. Not required if the configuration has a constructor with no arguments. (If there is no final field, etc. It is absolutely necessary if you use @Builder) @AllArgsConstructor Create a constructor that takes all fields as arguments. If NoArgsConstructor is specified, @Builder will not work unless this is also specified (@Builder automatically generates a constructor that takes all fields as arguments, but does not create a constructor for a class with xxxArgsConstructor. And it doesn't work.)

UserJpaRepository.java Interface required to use JPA implementation. Inherit JpaRepository and specify Entity class and primary key type. At runtime, the standard implementation provided by spring-data-jpa called SimpleJpaRepository is injected by the DI container, so there is no need to write an implementation class.

UserJpaRepository.java


package com.example.springapi.infrastructure.repository;

import com.example.springapi.infrastructure.entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 *Interface for using JPA
 */
public interface UserJpaRepository extends JpaRepository<UserEntity, String> {
}

UserRepositoryImpl.java Implementation class of UserRepository interface defined in domain layer. The actual processing is done by SimpleJpaRepository.

UserRepositoryImpl.java


package com.example.springapi.infrastructure.repository;

import com.example.springapi.domain.object.User;
import com.example.springapi.domain.repository.UserRepository;
import com.example.springapi.infrastructure.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Optional;

/**
 *Persistence implementation class
 *Convert domain object to Entity and wrap JPA
 */
@Repository
@RequiredArgsConstructor
public class UserRepositoryImpl implements UserRepository {

    @NonNull
    private final UserJpaRepository userJpaRepository;

    /**
     * {@inheritDoc}
     */
    @Override
    public Optional<User> findById(String id) {
        return this.userJpaRepository.findById(id)
                .map(UserEntity::toDomainUser);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public User save(User user) {
        return this.userJpaRepository.save(UserEntity.build(user))
                .toDomainUser();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void deleteById(String id) {
        this.userJpaRepository.deleteById(id);
    }
}

@Repository Another name for @Compornent. With @Service.

Recommended Posts

Implement REST API with Spring Boot and JPA (Infrastructure layer)
Implement REST API with Spring Boot and JPA (Application 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
Implement GraphQL 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
Connect to database with spring boot + spring jpa and CRUD operation
[Beginner] Let's write REST API of Todo application with Spring Boot
Creating REST APIs with Spring JPA Data with REST and Lombok incredibly easy.
HTTPS with Spring Boot and Let's Encrypt
Implement CRUD with Spring Boot + Thymeleaf + MySQL
Implement paging function with Spring Boot + Thymeleaf
Implementation method for multi-data source with Spring boot (Mybatis and Spring Data JPA)
Try to implement login function with Spring Boot
Create a web api server with spring boot
Download with Spring Boot
Testing JPA entities and repositories using Spring Boot @DataJpaTest
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
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
Hello World with Spring Boot
Spring with Kotorin --8 Repository layer
Get started with Spring boot
Hello World with Spring Boot!
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
Spring Boot starting with Docker
Hello World with Spring Boot
Set cookies with Spring Boot
REST API testing with REST Assured
Use Spring JDBC with Spring Boot
With Spring boot, password is hashed and member registration & Spring security is used to implement login function.
Add module with Spring Boot
Getting Started with Spring Boot
Link API with Spring + Vue.js
Create microservices with Spring Boot
Domain Driven Development with Java and Spring Boot ~ Layers and Modules ~
Send email with spring boot
8 things to insert into DB using Spring Boot and JPA
Let's find out how to receive in Request Body with REST API of Spring Boot