[문제점]: 현재 유저 이미지,이름,이메일등을 모두 한꺼번에 바꿔야하는 식이다.
[요구사항]: 이미지만 바꾸던지, 이름이랑 이메일만 바꾸던지의 식으로 효율적으로 바꾸자.
[수정전 코드]
@Override
public User update(UUID userId,UserRequestDto userUpdateDto) {
//선택적으로 프로필 이미지를 할수도 있고 안할 수 도 있는거임.
//BinaryContent 자체는 수정이 안됨.
//user에서 profileId를 수정하는식으로 해야됨.
User user = userRepository.findById(userId)
.orElseThrow(() -> new NoSuchElementException("User with id " + userId + " not found"));
//유저의 이미지,이름,비밀번호 이런 모든걸 한번에 다 바꾼다.
user.update(userUpdateDto.username(), userUpdateDto.email(), userUpdateDto.password(),user.getProfileId());
if (userUpdateDto.binaryContentDto() != null) {
BinaryContentRequestDto dto = userUpdateDto.binaryContentDto();
BinaryContent newProfile = new BinaryContent(
userId,//프로필 소유자 id
null,
dto.data(),
dto.contentType(),
dto.fileName()
);
binaryContentRepository.save(newProfile);
user.setProfileId(newProfile.getId());
}
return userRepository.save(user);
}
main에서 바꾸고싶은것에만 값을 넣고, 아닌것에는 null을 넣었을때
null로 넣는게 null로 들어가는게 아니라 기존값으로 유지가 되게 하면 됨.
user.update()메소드 check
[User내 update() 수정후]
public void update(String newUsername, String newEmail, String newPassword, UUID newProfileId) {
boolean anyValueUpdated = false;
if (newUsername != null && !newUsername.equals(this.userName)) {//이름이 null이 아니고 기존꺼와 같지 않을때 변경.
this.userName = newUsername;
anyValueUpdated = true;
}
if (newEmail != null && !newEmail.equals(this.email)) {
this.email = newEmail;
anyValueUpdated = true;
}
if (newPassword != null && !newPassword.equals(this.password)) {
this.password = newPassword;
anyValueUpdated = true;
}
if (anyValueUpdated) {
this.updatedAt = Instant.now();
}
if(newProfileId != null && !newProfileId.equals(this.profileId)) {
this.profileId = newProfileId;
}
}
null이 아닐때와 기존값이랑 다를때만 변경되도록 로직을 짰다.
즉, null이나 기존값과 같은 값이 들어오면 변경을 안한다.
'코드잇 스프린트 > 실습' 카테고리의 다른 글
| PostgreSQL DB 와 Spring Boot(InteliJ) 연동하기 (0) | 2026.03.03 |
|---|---|
| [sprint5] 디스코드 어플리케이션 채널 생성시 NPE 발생 (0) | 2026.02.23 |
| ReadStatus,UserStatus,BinaryContent 도메인 추가(왜 추가하는거고, 어떤 역할을 하는지?) (0) | 2026.01.28 |
| 피드백) 단건조회는 null 반환 가능성이 있어 Optional로 래핑해라 (0) | 2026.01.21 |
| 간단한 디스코드 프로그램 만들기_ 피드백3(매개변수 변경 ,메서드 이관) (1) | 2026.01.15 |