blob: 3d8b7ddd04bfdb29a1625c3e689b40bb6acfbf28 [file] [log] [blame]
2230110243e9dfe2025-05-17 16:27:12 +08001package com.pt.service;
2
3import com.pt.entity.Comment;
4import com.pt.repository.CommentRepository;
5import org.springframework.beans.factory.annotation.Autowired;
6import org.springframework.stereotype.Service;
7
8import java.util.List;
9
10@Service
11public class CommentService {
12
13 @Autowired
14 private CommentRepository commentRepository;
15
16 public CommentService(CommentRepository commentRepository) {
17 this.commentRepository = commentRepository;
18 }
19
20 public void addComment(String content, String username, int postId) {
21 Comment comment = new Comment();
22 comment.setContent(content);
23 comment.setWriter(username);
24 comment.setParentPost(postId);
25 commentRepository.save(comment);
26 }
27
28 public void deleteComment(int commentId) {
29 commentRepository.deleteById(commentId);
30 }
31
32 public List<Comment> getCommentsByPostId(int postId) {
33 List<Comment> comments = commentRepository.findByParentPost(postId);
34 comments.sort(
35 // Sort comments by publish date in descending order
36 (c1, c2) -> c2.getPublishDate().compareTo(c1.getPublishDate())
37 );
38 return comments;
39 }
40}