일정 관리 앱을 다시 만들어보는 과제를 수행하던 도중,
public UserResponseDto findUserById(Long id) {
User findUser = userRepository.findById(id);
return new UserResponseDto(findUser.getEmail(), findUser.getUsername());
}
incompatible types: Optional<User> cannot be converted to User
User findUser = userRepository.findById(id); 에러가 발생했다.
userRepository.findById(id)는 Optional<User>를 반환하기 때문에 직접 User 타입 변수에 할당할 수 없었다.
public UserResponseDto findUserById(Long id) {
Optional<User> optionalUser = userRepository.findById(id);
if(optionalUser.isEmpty()){
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "ID가 존재하지 않습니다.");
}
User findUser = optionalUser.get();
return new UserResponseDto(findUser.getEmail(), findUser.getUsername());
}
Optional<User>는 값이 존재할 수도 있고 존재하지 않을 수도 있는 객체이기 때문에 isEmpty()로 값이 없을 경우를 처리하고 값이 있을 때만 get()을 호출하여 값을 추출해주었다.
'내배캠' 카테고리의 다른 글
| 최종 프로젝트 트러블슈팅(2) - 순환 참조 문제 (0) | 2025.01.09 |
|---|---|
| 최종 프로젝트 트러블슈팅(1) - pageable (0) | 2025.01.09 |
| 팀 프로젝트 트러블슈팅 - 뉴스피드 프로젝트 (0) | 2024.11.21 |
| 개인과제 트러블슈팅 - 일정 관리 앱 Develop (0) | 2024.11.15 |
| 개인과제 트러블슈팅 - 일정 관리 앱 (0) | 2024.11.08 |