完成评论的基本的功能
Change-Id: I798126b0411b49b67111420247cb9884f1b41411
diff --git a/src/main/java/com/pt/service/CommentService.java b/src/main/java/com/pt/service/CommentService.java
new file mode 100644
index 0000000..3d8b7dd
--- /dev/null
+++ b/src/main/java/com/pt/service/CommentService.java
@@ -0,0 +1,40 @@
+package com.pt.service;
+
+import com.pt.entity.Comment;
+import com.pt.repository.CommentRepository;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.util.List;
+
+@Service
+public class CommentService {
+
+ @Autowired
+ private CommentRepository commentRepository;
+
+ public CommentService(CommentRepository commentRepository) {
+ this.commentRepository = commentRepository;
+ }
+
+ public void addComment(String content, String username, int postId) {
+ Comment comment = new Comment();
+ comment.setContent(content);
+ comment.setWriter(username);
+ comment.setParentPost(postId);
+ commentRepository.save(comment);
+ }
+
+ public void deleteComment(int commentId) {
+ commentRepository.deleteById(commentId);
+ }
+
+ public List<Comment> getCommentsByPostId(int postId) {
+ List<Comment> comments = commentRepository.findByParentPost(postId);
+ comments.sort(
+ // Sort comments by publish date in descending order
+ (c1, c2) -> c2.getPublishDate().compareTo(c1.getPublishDate())
+ );
+ return comments;
+ }
+}