2022-04-21 TIL

이창호·2022년 4월 21일
0

프로그래머스 백엔드 데브코스 32일차

Spring boot part3

DTO를 사용

만약 어떤 컨트롤러 메서드에 @PostMapping을 통해 요청이 온다 하자.

이때, @ReuqestBody를 붙인 매개변수 객체에 데이터가 담기질 않는다.

이유는 바로 Cannot construct instance of ... (no Creators, like default constructor, exist)인 것이다.

이 때 해결 방법은 DTO를 만들어 주는 것!

    @PostMapping(path = "/api/v1/customers/{customerId}")
    @ResponseBody
    public Customer findCustomer(
    		@PathVariable("customerId") UUID customerId, @RequestBody Customer customer) {
        logger.info("Got customer save request {}", customer);
        return customer;
    }
public record CustomerDto(UUID customerId, 
                          String name, 
                          String email, 
                          LocalDateTime lastLoginAt,
                          LocalDateTime createdAt) {
    static CustomerDto of(Customer customer) {
        return new CustomerDto(
                customer.getCustomerId(), 
                customer.getName(), 
                customer.getEmail(), 
                customer.getLastLoginAt(), 
                customer.getCreatedAt());
    }
}
profile
이타적인 기회주의자

0개의 댓글