45. 응답 DTO - 회원정보 조회 만들기v7

송민경's avatar
Mar 21, 2024
45. 응답 DTO - 회원정보 조회 만들기v7

1. 회원정보 조회

  • 필요한 내용 : username, password, email
  • 뿌릴 것 : username, email
 
notion image
 

2. UserResponse 만들어서 DTO 만들기

  • entity를 DTO로 만들어야 함
  • 내가 NEW하기 위한 기본 풀 생성자를 만들어야 함
package shop.mtcoding.blog.user; import lombok.Data; public class UserResponse { @Data public static class DTO { // 제일 기본 DTO private int id; private String username; private String email; } }
  • 생성자에 User 객체를 집어넣으면 됨
package shop.mtcoding.blog.user; import lombok.Data; public class UserResponse { @Data public static class DTO { // 제일 기본 DTO private int id; private String username; private String email; public DTO(User user) { this.id = user.getId(); this.username = user.getUsername(); this.email = user.getEmail(); } } }
 

3. UserController 에서 userinfo 수정하기

package shop.mtcoding.blog.user; import jakarta.servlet.http.HttpSession; import lombok.RequiredArgsConstructor; import org.springframework.data.repository.query.Param; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import shop.mtcoding.blog._core.utils.ApiUtil; @RequiredArgsConstructor @RestController public class UserController { private final UserService userService; private final HttpSession session; @GetMapping("/api/user/{id}") public ResponseEntity<?> userinfo(@PathVariable Integer id) { UserResponse.DTO respDTO = userService.lookUp(id); return ResponseEntity.ok(new ApiUtil(respDTO)); } }
  • UserService 에서 lookUp() 수정하기
package shop.mtcoding.blog.user; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import shop.mtcoding.blog._core.errors.exception.Exception400; import shop.mtcoding.blog._core.errors.exception.Exception401; import shop.mtcoding.blog._core.errors.exception.Exception404; import shop.mtcoding.blog.board.Board; import java.util.List; import java.util.Optional; @RequiredArgsConstructor @Service // IoC에 등록 public class UserService { // 컨트롤러는 서비스가, 서비스는 레파지토리가 필요함 - 의존 관계 private final UserJPARepository userJPARepository; public UserResponse.DTO lookUp(int id){ // 회원조회하 User user = userJPARepository.findById(id) .orElseThrow(() -> new Exception404("회원정보를 찾을 수 없습니다.")); return new UserResponse.DTO(user); //엔티티 생명 종료 } public UserResponse.DTO update (int id, UserRequest.UpdateDTO reqDTO) { User user = userJPARepository.findById(id) .orElseThrow(() -> new Exception404("회원정보를 찾을 수 없습니다")); user.setPassword(reqDTO.getPassword()); user.setEmail(reqDTO.getEmail()); // userJPARepository.save(user); return new UserResponse.DTO(user); } // 더티체킹 }
notion image
Share article

vosw1