BasicUserService내 update 기능 피드백.

2026. 1. 29. 17:22·코드잇 스프린트/실습

[문제점]: 현재 유저 이미지,이름,이메일등을 모두 한꺼번에 바꿔야하는 식이다.

 

[요구사항]: 이미지만 바꾸던지, 이름이랑 이메일만 바꾸던지의 식으로 효율적으로 바꾸자.

 

[수정전 코드]

 @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
'코드잇 스프린트/실습' 카테고리의 다른 글
  • PostgreSQL DB 와 Spring Boot(InteliJ) 연동하기
  • [sprint5] 디스코드 어플리케이션 채널 생성시 NPE 발생
  • ReadStatus,UserStatus,BinaryContent 도메인 추가(왜 추가하는거고, 어떤 역할을 하는지?)
  • 피드백) 단건조회는 null 반환 가능성이 있어 Optional로 래핑해라
과컴
과컴
벡엔드 개발자 최소기준 맞추겠습니다.
  • 과컴
    곽의 프로그램
    과컴
  • 전체
    오늘
    어제
    • 분류 전체보기 (76)
      • 위클리페이퍼 (6)
      • 파이썬 (4)
      • 코드잇 스프린트 (48)
        • Spring 이론 (7)
        • Java이론 (11)
        • 실습 (23)
      • 백엔드 개발자 최소기준 (1)
      • 코딩테스트 (5)
        • 알고리즘 (0)
        • SQL (1)
      • Git (5)
      • 스프링부트 핵심가이드 (1)
      • 트러블 슈팅 (2)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    백준1152
    혼공파
    파이썬입문
    문자열
    파이썬
    백준1075번
    백준2576
    파이썬기초
    백준브론즈
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.6
과컴
BasicUserService내 update 기능 피드백.
상단으로

티스토리툴바