Home ๐Ÿ” ๊ฒŒ์‹œ๋ฌผ ๋‹จ์ผ ์กฐํšŒ stream ์‚ฌ์šฉํ•ด ๊ตฌํ˜„
Post
Cancel

๐Ÿ” ๊ฒŒ์‹œ๋ฌผ ๋‹จ์ผ ์กฐํšŒ stream ์‚ฌ์šฉํ•ด ๊ตฌํ˜„



1
2
3
4
5
6
7
  //๊ฒŒ์‹œ๊ธ€ ์ „์ฒด ์กฐํšŒ
  @Transactional
  public List<AllPostResDto> getAllPost() {
    List<Post> postList = postRepository.findAll();
    return postList.stream()
        .map(AllPostResDto::new).toList();
    }

โฌ‡๏ธ

1
2
3
4
5
6
7
8
9
  //๊ฒŒ์‹œ๊ธ€ ์ „์ฒด ์กฐํšŒ
  @Transactional
  public List<AllPostResDto> getAllPost() {
    List<Post> postList = postRepository.findAll();
    return  postList.stream()
        .map((post) -> new AllPostResDto(post))
        .toList();
  }



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    // ๊ฒŒ์‹œ๊ธ€ ์ƒ์„ธ ์กฐํšŒ
    @Transactional(readOnly = true)
    public PostResponseDto getOnePost(Long id) {
        Post post = validateCheck.getPostIfExists(id);

        // ๊ฒŒ์‹œ๊ธ€ ์ƒ์„ธ ์กฐํšŒ ์‹œ ๋Œ“๊ธ€๋„ ํ•จ๊ป˜ ์กฐํšŒ
        List<Comment> comments = commentRepository.findByPostId(id);
        List<CommentResDto> commentList = new ArrayList<>();
        for (Comment comment : comments) {
            commentList.add(CommentResDto.builder()
                    .id(comment.getId())
                    .commenter(comment.getMember().getEmail())
                    .content(comment.getContent())
                    .modifiedAt(comment.getModifiedAt())
                    .build()
            );
        }
        
        return PostResponseDto.builder()
        .id(post.getId())
        .title(post.getTitle())
        .content(post.getContent())
        .email(post.getMember().getEmail())
        .modifiedAt(post.getModifiedAt())
        .comments(commentList)
        .build();
    }

โฌ‡๏ธ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    // ๊ฒŒ์‹œ๊ธ€ ์ƒ์„ธ ์กฐํšŒ
    @Transactional(readOnly = true)
    public PostResponseDto getOnePost(Long id) {
        Post post = validateCheck.getPostIfExists(id);


        // ๊ฒŒ์‹œ๊ธ€ ์ƒ์„ธ ์กฐํšŒ ์‹œ ๋Œ“๊ธ€๋„ ํ•จ๊ป˜ ์กฐํšŒ
       List<CommentResDto> commentResDtos = commentRepository.findByPostId(id)
            .stream()
            .map(comment -> CommentResDto.builder()
                    .id(comment.getId())
                    .commenter(comment.getMember().getEmail())
                    .content(comment.getContent())
                    .modifiedAt(comment.getModifiedAt())
                    .build())
            .toList();

        
        return PostResponseDto.builder()
        .id(post.getId())
        .title(post.getTitle())
        .content(post.getContent())
        .email(post.getMember().getEmail())
        .modifiedAt(post.getModifiedAt())
        .comments(commentList)
        .build();
    }



This post is licensed under CC BY 4.0 by the author.

๐Ÿ” ๊ฒŒ์‹œ๋ฌผ ์‚ญ์ œ์‹œ ๋Œ“๊ธ€๋„ ํ•จ๊ป˜ ์‚ญ์ œ ๊ตฌํ˜„

/Database/ SQL join