필요한 정보

username

email

userId

Untitled

package shop.mtcoding.blog.user;

import lombok.Data;

public class UserResponse {

    @Data
    public static class DTO {
        private int id;
        private String username;
        private String email;

        // 응답 DTO 는 생성자를 만들어야 한다.
        // DTO 의 this 가 아니라 Entity 를 DTO 로 바꿔야 한다.
        public DTO(User user) {
            this.id = user.getId();
            this.username = user.getUsername();
            this.email = user.getEmail();
        }
    }
}

서비스에서 DTO를 쓰는법

// 회원정보 조회
public UserResponse.DTO findById(int id) {
    User user = userJAPRepository.findById(id)
            .orElseThrow(() -> new Exception404("회원정보를 찾을 수 없습니다"));
    return new UserResponse.DTO(user); // 엔티티 생명 종료
}

컨트롤러 수정

// 회원정보 조회
@GetMapping("/api/users/{id}")
public ResponseEntity<?> userinfo(@PathVariable Integer id) {
    UserResponse.DTO requestDTO = userService.findById(id);
    return ResponseEntity.ok(new ApiUtil(requestDTO));
}