comment
Change-Id: Iafdf1c3e19b18faa75e96fde1acad93fda6f77f0
diff --git a/src/main/java/com/example/g8backend/service/ICommentService.java b/src/main/java/com/example/g8backend/service/ICommentService.java
new file mode 100644
index 0000000..ea82f8f
--- /dev/null
+++ b/src/main/java/com/example/g8backend/service/ICommentService.java
@@ -0,0 +1,16 @@
+package com.example.g8backend.service;
+
+import com.example.g8backend.entity.Comment;
+
+import java.util.List;
+
+public interface ICommentService {
+
+ void createComment(Long postId, Long userId, String content, Long parentCommentId);
+
+ List<Comment> getCommentsByPostId(Long postId);
+
+ List<Comment> getReplies(Long parentCommentId, int depth);
+
+ boolean deleteComment(Long commentId);
+}
diff --git a/src/main/java/com/example/g8backend/service/impl/CommentServiceImpl.java b/src/main/java/com/example/g8backend/service/impl/CommentServiceImpl.java
new file mode 100644
index 0000000..fae8a1f
--- /dev/null
+++ b/src/main/java/com/example/g8backend/service/impl/CommentServiceImpl.java
@@ -0,0 +1,70 @@
+package com.example.g8backend.service.impl;
+
+import com.example.g8backend.entity.Comment;
+import com.example.g8backend.mapper.CommentMapper;
+import com.example.g8backend.service.ICommentService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+
+
+@Service
+public class CommentServiceImpl implements ICommentService {
+
+ @Autowired
+ private CommentMapper commentMapper;
+
+ @Override
+ public void createComment(Long postId, Long userId, String content, Long parentCommentId) {
+ Comment comment = new Comment();
+ comment.setPostId(postId);
+ comment.setUserId(userId);
+ comment.setContent(content);
+ comment.setParentCommentId(parentCommentId); // 如果是顶级评论为NULL
+ commentMapper.insert(comment);
+ }
+
+ @Override
+// 获取帖子下的所有评论(顶级评论及其子评论)
+ public List<Comment> getCommentsByPostId(Long postId) {
+ // 获取顶级评论
+ List<Comment> topLevelComments = commentMapper.findTopLevelCommentsByPostId(postId);
+
+ // 获取每个评论的子评论
+ for (Comment comment : topLevelComments) {
+ List<Comment> replies = getReplies(comment.getCommentId(), 0); // 初始深度为0
+ comment.setReplies(replies); // 设置子评论
+ }
+
+ return topLevelComments;
+ }
+
+
+ // 获取某个评论的子评论,并设置递归深度
+ public List<Comment> getReplies(Long parentCommentId, int depth) {
+ // 如果递归深度超过最大限制,停止递归
+ if (depth > 5) {
+ return new ArrayList<>();
+ }
+
+ // 获取当前评论的子评论
+ List<Comment> replies = commentMapper.findRepliesByParentCommentId(parentCommentId);
+
+ // 遍历每个子评论
+ for (Comment reply : replies) {
+ // 递归获取该子评论的子评论
+ List<Comment> childReplies = getReplies(reply.getCommentId(), depth + 1); // 深度加1
+ reply.setReplies(childReplies); // 设置该子评论的子评论
+ }
+
+ return replies;
+ }
+
+
+ @Override
+ public boolean deleteComment(Long commentId) {
+ return commentMapper.deleteById(commentId) > 0;
+ }
+}