본문 바로가기

Computer Science/Spring

[Spring] Optional 객체 여부에 따른 map 사용법

1)객체가 Optional 객체인 경우

- JPA를 활용하면 단일 객체 리턴에 대해서는 모두 Optional 객체로 반환한다.

( ※ 참고로 JPA 에서 List<ObjectName> 로 리턴할 때는, List 가 비어있으면 Optional 객체가 아닌 Null로 리턴한다.)

- 따라서 아래 mailRepository.findById 는 Optional 객체를 리턴하며 따로 Optional.of 나 Optional.ofNullable 를 활용할 필요는 없다.

 

Mail mail = this.mailRepository.findById(mailRequestDTO.getId().longValue())
                .map(m -> {
                            Mail newMail;
                            newMail = m;
							//
                            ... Setting ... 
                            //
                            return newMail;
                        })
                .orElseGet(() -> new Mail(mailRequestDTO, folder, ssoId, TIMEZONE));

 

2) 객체가 Optional 객체가 아닌 경우

- 아래 requestDto 에서 가져오는 getId()는 Optional 객체가 아니다.

- 따라서, Optional.ofNullable 로 감싸줘 map 을 활용하였다.

 

String ssoId = AuthUtil.getCurrentUserEntitiy().getLogin();
Notice notice = Optional.ofNullable(requestDto.getId())
        .map(v -> noticeRepository.getOne(Long.valueOf(v)))
        .map(n -> Notice.of(requestDto, n.getCreatedBy(), n.getCreatedDate(), ssoId))
        .orElseGet(()-> Notice.of(requestDto, ssoId, ssoId));

 

반응형