SpringBoot后端开发评论功能+分类页面+标签页面
评论功能
评论功能主要是要有评论实体,然后将每个评论实体与一个确定的新闻实体挂钩,另外还需要有评论回复的功能,所以对于每一条评论都需要携带一个回复评论的List以及一个父评论(也就是回复的评论),如果父评论为-1则说明是顶级的评论。
新建实体
Comment.java:
@Entity
@Table(name = "t_comment")
public class Comment {
@Id //主键标识
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String nickname;
private String email;
private String content;
private String avatar;
@Temporal(TemporalType.TIMESTAMP)
private Date createTime;
@ManyToOne
private News news;
//回复集合
@OneToMany(mappedBy = "parentComment")
private List<Comment> replyComments = new ArrayList<>();
@ManyToOne
private Comment parentComment;
private boolean adminComment;
//省略get和set方法
}
新建CommentRepository
CommentRepository.java:
//CommentRepository.java
public interface CommentRepository extends JpaRepository<Comment,Long> {
//符合有NewsId并且父级评论为空的评论(也就是顶级的评论
List<Comment> findByNewsIdAndParentCommentNull(Long newId, Sort sort);
}
新建服务
CommentService.java:
//CommentService.java
public interface CommentService {
List<Comment> listCommentByNewId(Long NewId);
Comment saveComment(Comment comment);
}
CommentServiceImpl.java:
//CommentServiceImpl.java
@Service
public class CommentServiceImpl implements CommentService {
@Autowired
private CommentRepository commentRepository;
@Override
public List<Comment> listCommentByNewId(Long newId) {
Sort sort = Sort.by("createTime");
List<Comment> comments = commentRepository.findByNewsIdAndParentCommentNull(newId,sort);
return eachComment(comments);
}
private List<Comment> eachComment