我试图在单个请求查询中获取评论及其子项数,具体取决于文章和评论父母。
这是我的评论实体:
@Entity
@Builder
@Data
public class Comment extends AbstractEntity {
@Id
@GeneratedValue
private Long id;
private String firstname;
private String lastname;
private String email;
private String title;
private Integer depth;
@Lob
private String message;
@ManyToOne(fetch = FetchType.LAZY)
@JsonIgnore
private Article article;
@ManyToOne(fetch = FetchType.LAZY)
@JsonIgnore
private Comment parent;
}
我将如何在SQL中执行:
String query = "select c.*, (SELECT COUNT(p.id) from comment p where p.id = c.parent_id) from comment c where c.article_id = ?1 and (c.parent_id is null or c.parent_id =?2) ";
我在我的存储库中使用@Query尝试了几个选项,我也尝试使用QueryDSL,但我没有足够的经验。现在,我每行都要进行两次查询,一次是查看评论,另一次是查看孩子的数量。
这是我的存储库:
@Repository
@Transactional
public interface CommentRepository extends JpaRepository<Comment, Long> {
List<Comment> findByArticle(Article article);
List<Comment> findByArticleAndParent(Article article, Comment comment);
Long countByParent(Comment comment);
}
这是我的控制器:
@RequestMapping(value = "/article/{slug}/{id}/comment", method = RequestMethod.POST)
public String comments(@PathVariable(value = "id") Long id, @PathVariable(value = "slug") String slug,
@RequestParam(required = false, value = "parent_id") Long parentId
, ModelMap modelMap) {
CommentService commentService = this.blogService.getCommentService();
Comment parent = Objects.isNull(parentId) ? null : commentService.findOneById(parentId);
List<Comment> comments = blogService.comments(id, slug, parent);
Map<Comment, Long> commentsAndCountChildren = comments.stream()
.collect(Collectors.toMap(Function.identity(), commentService::countByParent));
modelMap.addAttribute("comments", commentsAndCountChildren)
;
return "blog/comments";
}
我正在尝试开发一个懒惰的评论系统(比如facebook),每当客户点击按钮时我们会再显示5条评论。评论可以有一个孩子,并且要查看此评论的5个下一个子评论,用户需要再次点击另一个按钮等。
谢谢。