新闻评论功能实现
1.新建实体类
在pojo目录下新建一个Comment的实体类,主要包含昵称、邮箱、评论内容、头像和创建时间,接着就是声明实体间对应的关系
@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> replyComment = new ArrayList<>();
@ManyToOne
private Comment parentComment;
//管理员评论
private boolean adminComment;
public Comment() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public News getNews() {
return news;
}
public void setNews(News news) {
this.news = news;
}
public List<Comment> getReplyComment() {
return replyComment;
}
public void setReplyComment(List<Comment> replyComment) {
this.replyComment = replyComment;
}
public Comment getParentComment() {
return parentComment;
}
public void setParentComment(Comment parentComment) {
this.parentComment = parentComment;
}
public boolean isAdminComment() {
return adminComment;
}
public void setAdminComment(boolean adminComment) {
this.adminComment = adminComment;
}
@Override
public String toString() {
return "Comment{" +
"id=" + id +
", nickname='" + nickname + '\'' +
", email='" + email + '\'' +
", content='" + content + '\'' +
", avatar='" + avatar + '\'' +
", createTime=" + createTime +
", news=" + news +
", replyComment=" + replyComment +
", parentComment=" + parentComment +
", adminComment=" + adminComment +
'}';
}
}
2.新建repository
在dao目录下新建一个CommentRepository,继承jpa,并且声明一个用来查找父级评论的方法
public interface CommentRepository extends JpaRepository<Comment,Long> {
//根据新闻id和父级评论是空查询
// @Query
List findByNewsIdAndParentCommentNull(Long newId, Sort sort);
}
3.新建Service
在Service目录下新建一个CommentService的接口方法,声明发表评论方法和查找所有评论方法,保存评论的方法实现只需要查找到是否有父级评论,并调用jpa保存到数据库中即可,但按父子级进行评论的展示需要循环迭代找出所有子代评论,并申请一个临时存放区域,再按照父->子的方向保存到一个commentsView链表中
public interface CommentService {
//发表评论
Comment saveComment(Comment comment);
//展示所有评论
List<Comment> listCommentByNewId(Long newId);
}
之后再在CommentServiceImpl中实现该方法,这里
@Service
public class CommentServiceImpl implements CommentService {
@Autowired
CommentRepository commentRepository;
@Override
public Comment saveComment(Comment comment) {
Long parentCommentId = comment.getParentComment().getId();
if(parentCommentId!=-1){ //有父级评论
comment.setParentComment(commentRepository.findById(parentCommentId).orElse(null));
}else{
comment.setParentComment(null);
}
comment.setCreateTime(new Date());
return commentRepository.save(comment);
}
@Override
public List<Comment> listCommentByNewId(Long newId) {
Sort sort = Sort.by("createTime");
List<Comment> comments = commentRepository.findByNewsIdAndParentCommentNull(newId,sort);
System.out.println("运行到listCommentByNewId");
return eachComment(comments);
}
//循环查找所有评论
private List<Comment> eachComment(List<Comment> comments){
List<Comment> commentsView = new ArrayList<>();
System.out.println("eachComment");
for(Comment comment:comments){
Comment c = new Comment();
BeanUtils.copyProperties(comment,c);
commentsView.add(c);
}
//合并评论的各层子代到第一代集合
combineChildrenComment(commentsView);
return commentsView;
}
private void combineChildrenComment(List<Comment> comments){
System.out.println("combineChildrenComment");
for(Comment comment:comments){
List<Comment> replies = comment.getReplyComment();
for(Comment reply : replies){
//循环迭代,找出子代 存放在临时存放区
recursively(reply);
}
comment.setReplyComment(tempReplies);
//清除临时存放区
tempReplies = new ArrayList<>();
}
}
//临时找出子代
private List<Comment> tempReplies = new ArrayList<>();
private void recursively(Comment comment){
tempReplies.add(comment); //顶节点添加到临时存放区
if(comment.getReplyComment().size()>0){
List<Comment> replies = comment.getReplyComment();
for(Comment reply:replies){
tempReplies.add(reply);
if(comment.getReplyComment().size()>0){
recursively(reply);
}
}
}
}
}
4.新建controller
在web目录下新建一个Controller,由于该部分功能针对所有用户,所以需要再全局web下进行创建,目前再界面中输入的只能是昵称和邮箱和评论,头像直接在controller中声明的,后续可改成在评论时自定义头像
@Controller
public class CommentController {
@Autowired
CommentService commentService;
@Autowired
NewService newService;
//保存
private String avatar = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1091405991,859863778&fm=26&gp=0.jpg";
@GetMapping("/comments/{newId}")
public String comments(@PathVariable Long newId, Model model){
System.out.println("运行到这里"+newId);
model.addAttribute("comments",commentService.listCommentByNewId(newId));
return "new::commentList";
}
@PostMapping("/comments")
public String post(Comment comment, HttpSession session){
Long newId = comment.getNews().getId();
comment.setNews(newService.getNew(newId));
User user = (User)session.getAttribute("user");
if(user!=null){
comment.setAdminComment(true);
}
comment.setAvatar(avatar);
commentService.saveComment(comment);
return "redirect:/comments/"+newId;
}
}
在该文件中,comments方法用来展示当前新闻的评论,这里的listCommentByNewId(newID)方法将直接从service中实现的方法返回的链表里按父子级进行评论展示,而post方法用于提交输入的评论,用到service中的save方法
标签功能实现
功能实现步骤和type差不多,只是在调用NewService处的方法传参不一样,需要对每种传参都进行方法实现
1.添加TagRepository方法
@Query(“select t from Tag t”)
List findTop(Pageable pageable);
2.添加TagService方法
//显示在主页
List listTagTop(Integer size);
在Impl中实现
@Override
public List listTagTop(Integer size) {
Sort sort = Sort.by(Sort.Direction.DESC,“newsList.size”);
Pageable pageable = PageRequest.of(0,size,sort);
return tagRepository.findTop(pageable);
}
3.新建TagShowController
在web目录下新建一个TagShowController
@Controller
public class TagShowController {
@Autowired
private NewService newService;
@Autowired
private TagService tagService;
@GetMapping("/tags/{id}")
public String tags(@PageableDefault(size = 8,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,
@PathVariable Long id, Model model){
List<Tag> tags = tagService.listTagTop(20);
if(id==-1){
id = tags.get(0).getId();
}
model.addAttribute("tags",tags);
model.addAttribute("page",newService.listNew(pageable));
model.addAttribute("activeTagId",id);
return "tags";
}
}
这里需要在NewService中新声明一个只有pageable参数的listNew方法,并在Impl中实现
//主页分页展示
Page listNew(Pageable pageable);
Impl实现
@Override
public Page listNew(Pageable pageable) {
return newRepository.findAll(pageable);
}