프로젝트/Trend-Pick

비어있을 수도 있는 객체의 조회 -> Optional 사용

chanhee01 2023. 7. 27. 16:56
@GetMapping("/post/{postId}") // 게시글 하나 클릭해서 들어가는 것
    public PostWithCommentDto createPost (@PathVariable ("postId") Long postId) {

        Post post = postService.findOne(postId);
        PostImg postImg = postImgService.findByPostId(postId);
        List<Comment> commentList = commentService.post_comment(postId);

        List<CommentDtoContent> commentDtoContents = commentList.stream()
                .map(c -> new CommentDtoContent(c.getContent(), c.getComment_member().getMemberImg().getImgUrl()))
                .collect((Collectors.toList()));

        return new PostWithCommentDto(post, postImg.getImgUrl(), commentDtoContents);
    }

게시글의 상세 페이지를 들어가는 로직이다.

 

이걸 그대로 동작시키면 오류가 발생한다. 그 이유는 사용자가 마이페이지에서 직접 대표사진을 수정하지 않았을 때에는 null로 들어가있기 때문에 NullPointException이 발생할 수도 있기 때문이다.

 

NullPointException 발생

 

사용자가 입력하지 않았다면 null 값이 들어가야하기 때문에 Optional로 감싸서 null이라면 null을 반환할 수 있게 해야한다.

@GetMapping("/post/{postId}") // 게시글 하나 클릭해서 들어가는 것
    public PostWithCommentDto createPost (@PathVariable ("postId") Long postId) {

        Post post = postService.findOne(postId);
        PostImg postImg = postImgService.findByPostId(postId);
        List<Comment> commentList = commentService.post_comment(postId);

        List<CommentDtoContent> commentDtoContents = commentList.stream()
                .map(c -> {
                    String imgUrl = Optional.ofNullable(c.getComment_member().getMemberImg())
                            .map(MemberImg::getImgUrl)
                            .orElse(null);
                    return new CommentDtoContent(c.getContent(), imgUrl);
                })
                .collect(Collectors.toList());

        return new PostWithCommentDto(post, postImg.getImgUrl(), commentDtoContents);
    }

람다식을 사용할 때 Optional.ofNullable을 사용해서 MemberImg의 imgUrl이 있으면 그걸 반환하고 아니면 null을 반환하는 로직이다.

Optional을 통해 사용자가 일일이 자신의 대표 사진을 설정하지 않더라도 null로 반환될 수 있게 해주었다. 이후에 null이 반환되면 기본 이미지로 설정되는 방법을 통해 기본 이미지를 보여주면 된다.

 

 

 

게시글 목록에도 같은 방법으로 적용

@GetMapping("/post_list")
    public List<PostDtoTitle> postList() {
        List<Post> findPosts = postService.findAllPost();

        List<PostImg> findPostImgs = postImgService.findAllPostImg();

        List<PostDtoTitle> postLists = findPosts.stream()
                .map(c -> {
                    String imgUrl = Optional.ofNullable(c.getPostImg())
                            .map(PostImg::getImgUrl)
                            .orElse(null);
                    return new PostDtoTitle(c.getTitle(), c.getContent(), c.getPostTime(), c.getPostImg().getImgUrl());
                })
                .collect((Collectors.toList()));


        return postLists;
    }

게시글 목록에서도 이와 같이 사진이 사용된다. 게시글 목록에 게시글의 대표사진이 나오는데, 사진을 안 넣었을 경우도 있기 때문에 Optional로 감싸서 null이면 null을 반환하고 imgUrl이 있으면 그 사진의 url을 반환하는 로직을 만들었다.

 

 

 

 

NullPointException이 발생했을 때 어떻게 해결해야 할지 막막했다.

 

스프링을 공부하고 있다지만 스프링은 결국 자바 기반으로 돌아가는 것이기 때문에 자바에서 지원하는 기능들을 사용하면 NullPointException을 해결할 수 있었다.

 

스프링을 잘한다는 것은 자바를 잘하는 것이 전제조건이 되어야되기 때문에 자바 기초 공부는 개발을 진행하더라도 계속해서 끊임없이 진행 되어야 한다.