feat(comment): 优化评论加载效率并添加回复功能
- 在 CommentRepository 中添加 findByParentIdInOrderByCreateTimeAsc 方法,实现批量查询子评论 - 重构 CommentServiceImpl 中的 findCommentsByMusicId 方法,提升评论加载效率 - 在前端 MusicDetail 组件中增加回复功能,支持二级评论和回复展开/收起 - 优化 WebSocket订阅逻辑,实现实时更新评论列表
This commit is contained in:
@@ -34,6 +34,14 @@ public interface CommentRepository extends JpaRepository<Comment, Long>, JpaSpec
|
||||
*/
|
||||
List<Comment> findByParentIdOrderByCreateTimeAsc(Long parentId);
|
||||
|
||||
/**
|
||||
* 根据父评论ID列表查询所有子评论
|
||||
*
|
||||
* @param parentIds 父评论ID列表
|
||||
* @return 子评论列表
|
||||
*/
|
||||
List<Comment> findByParentIdInOrderByCreateTimeAsc(List<Long> parentIds);
|
||||
|
||||
/**
|
||||
* 根据用户查询评论
|
||||
*
|
||||
|
||||
@@ -74,16 +74,28 @@ public class CommentServiceImpl implements CommentService {
|
||||
.map(this::convertToDTO)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// 获取子评论
|
||||
for (CommentDTO commentDTO : commentDTOs) {
|
||||
List<Comment> children = commentRepository.findByParentIdOrderByCreateTimeAsc(commentDTO.getId());
|
||||
if (!children.isEmpty()) {
|
||||
commentDTO.setChildren(children.stream()
|
||||
.map(this::convertToDTO)
|
||||
.collect(Collectors.toList()));
|
||||
} else {
|
||||
commentDTO.setChildren(new ArrayList<>());
|
||||
}
|
||||
// 优化:一次性获取所有子评论
|
||||
// 1. 获取所有父评论的ID
|
||||
List<Long> parentIds = commentDTOs.stream()
|
||||
.map(CommentDTO::getId)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// 2. 如果有父评论,则一次性查询出它们所有的子评论
|
||||
if (!parentIds.isEmpty()) {
|
||||
List<Comment> allChildren = commentRepository.findByParentIdInOrderByCreateTimeAsc(parentIds);
|
||||
|
||||
// 3. 将子评论按其父ID分组
|
||||
java.util.Map<Long, List<CommentDTO>> childrenMap = allChildren.stream()
|
||||
.map(this::convertToDTO)
|
||||
.collect(Collectors.groupingBy(CommentDTO::getParentId));
|
||||
|
||||
// 4. 将子评论列表设置到对应的父评论DTO中
|
||||
commentDTOs.forEach(parentDTO -> parentDTO.setChildren(
|
||||
childrenMap.getOrDefault(parentDTO.getId(), new ArrayList<>())
|
||||
));
|
||||
} else {
|
||||
// 如果没有父评论,确保children字段不是null
|
||||
commentDTOs.forEach(parentDTO -> parentDTO.setChildren(new ArrayList<>()));
|
||||
}
|
||||
|
||||
return new PageResult<>(
|
||||
|
||||
Reference in New Issue
Block a user