-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCommentService.java
More file actions
52 lines (39 loc) · 1.55 KB
/
CommentService.java
File metadata and controls
52 lines (39 loc) · 1.55 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.example.springhw32.service;
import com.example.springhw32.dto.CommentDto;
import com.example.springhw32.entity.Comment;
import com.example.springhw32.entity.Post;
import com.example.springhw32.repository.CommentRepository;
import com.example.springhw32.repository.PostRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;
@Service
@Transactional
@RequiredArgsConstructor
public class CommentService {
private final PostRepository postRepository;
private final CommentRepository commentRepository;
public CommentDto createComment(CommentDto commentDto, Long postId){
Post post = postRepository.findById(postId).orElseThrow();
Comment comment = new Comment();
comment.setContent(commentDto.getContent());
comment.setPost(post);
commentRepository.save(comment);
// 댓글 수 증가
post.setCommentCount(post.getCommentCount() + 1L);
postRepository.save(post);
return commentDto;
}
public List<CommentDto> findAllByPostId(Long postId){
return commentRepository.findAllByPost_PostId(postId).stream()
.map(this::convertToCommentDto)
.collect(Collectors.toList());
}
public CommentDto convertToCommentDto(Comment comment) {
CommentDto commentDto = new CommentDto();
commentDto.setContent(comment.getContent());
return commentDto;
}
}