一、概述

文档评论功能是知识库系统增强用户互动的重要手段,通过评论系统,用户可以对文档进行讨论、提问和反馈。

本文将详细介绍如何在kb-document服务中实现完整的文档评论功能。

1.1 功能定位

评论系统作为用户互动的核心功能,提供以下核心能力:

功能模块说明使用场景
评论创建发表对文档的评论或回复其他评论用户反馈、问题讨论
评论删除删除自己的评论撤回不当言论
点赞/取消点赞对评论进行点赞表示认同内容质量反馈
评论列表分页查看文档的所有评论评论浏览
评论回复对评论进行二级回复深度讨论
评论排序支持按时间或点赞数排序热门评论展示

1.2 评论系统设计要点

层级结构设计:

  • 支持两级评论结构:根评论 + 子评论(回复)
  • 最多支持两级,避免嵌套过深影响体验
  • 通过parentId和rootId字段实现层级关联

点赞系统设计:

  • 独立的点赞表tb_like支持多种目标类型
  • 通过targetType区分文档点赞和评论点赞
  • 防止重复点赞的唯一索引设计

计数策略:

  • 评论表冗余存储likeCount和replyCount
  • 通过数据库原子操作保证计数准确性
  • 避免频繁查询关联表影响性能

1.3 数据模型

文档 (Document)
    ├── 根评论1 (Comment, parentId=0)
    │   ├── 回复1 (Comment, parentId=根评论1.id, rootId=根评论1.id)
    │   └── 回复2 (Comment, parentId=根评论1.id, rootId=根评论1.id)
    ├── 根评论2 (Comment, parentId=0)
    └── ...

点赞表设计:

tb_like
    ├── 文档点赞 (targetType=1)
    └── 评论点赞 (targetType=2)

二、数据库设计

2.1 评论表结构

-- 评论表
DROP TABLE IF EXISTS `tb_comment`;
CREATE TABLE `tb_comment` (
    `id` BIGINT(20) PRIMARY KEY COMMENT '评论ID(雪花ID)',
    `document_id` BIGINT(20) NOT NULL COMMENT '文档ID',
    `parent_id` BIGINT(20) COMMENT '父评论ID',
    `root_id` BIGINT(20) COMMENT '根评论ID',

    `content` TEXT NOT NULL COMMENT '评论内容',

    `commenter_id` BIGINT(20) NOT NULL COMMENT '评论人ID',
    `commenter_name` VARCHAR(50) COMMENT '评论人姓名',
    `commenter_avatar` VARCHAR(500) COMMENT '评论人头像',

    `reply_to_user_id` BIGINT(20) COMMENT '回复给谁(用户ID)',
    `reply_to_user_name` VARCHAR(50) COMMENT '回复给谁(用户姓名)',

    `status` TINYINT NOT NULL DEFAULT 1 COMMENT '状态:0-隐藏,1-正常',

    `like_count` INT DEFAULT 0 COMMENT '点赞数',
    `reply_count` INT DEFAULT 0 COMMENT '回复数',

    `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    `deleted` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '删除标记',

    KEY `idx_document_id` (`document_id`),
    KEY `idx_parent_id` (`parent_id`),
    KEY `idx_root_id` (`root_id`),
    KEY `idx_commenter_id` (`commenter_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='评论表';

2.2 点赞表结构

-- 点赞表
DROP TABLE IF EXISTS `tb_like`;
CREATE TABLE `tb_like` (
    `id` BIGINT(20) PRIMARY KEY COMMENT '点赞ID',
    `target_id` BIGINT(20) NOT NULL COMMENT '目标ID(文档或评论)',
    `target_type` TINYINT NOT NULL COMMENT '目标类型:1-文档,2-评论',
    `user_id` BIGINT(20) NOT NULL COMMENT '用户ID',

    `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',

    UNIQUE KEY `uk_target_user_type` (`target_id`, `user_id`, `target_type`),
    KEY `idx_target_id` (`target_id`),
    KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='点赞表';

2.3 字段说明

评论表 (tb\_comment) 字段说明:

字段类型说明必填默认值
idBIGINT评论ID(雪花ID)是自动生成
document\_idBIGINT文档ID是-
parent\_idBIGINT父评论ID(0表示根评论)否0
root\_idBIGINT根评论ID否-
contentTEXT评论内容是-
commenter\_idBIGINT评论人ID是-
commenter\_nameVARCHAR(50)评论人姓名(冗余)否-
commenter\_avatarVARCHAR(500)评论人头像(冗余)否-
reply\_to\_user\_idBIGINT回复给谁的用户ID否-
reply\_to\_user\_nameVARCHAR(50)回复给谁的用户姓名(冗余)否-
statusTINYINT状态(0-隐藏,1-正常)是1
like\_countINT点赞数(冗余)是0
reply\_countINT回复数(冗余)是0
created\_atDATETIME创建时间是CURRENT\_TIMESTAMP
updated\_atDATETIME更新时间是自动更新
deletedTINYINT删除标记是0

点赞表 (tb\_like) 字段说明:

字段类型说明必填默认值
idBIGINT点赞ID是自动生成
target\_idBIGINT目标ID(文档ID或评论ID)是-
target\_typeTINYINT目标类型(1-文档,2-评论)是-
user\_idBIGINT用户ID是-
created\_atDATETIME创建时间是CURRENT\_TIMESTAMP

2.4 索引设计

评论表索引:

  • 主键索引:id - 主键唯一标识
  • 普通索引:idx_document_id - 加速按文档查询评论
  • 普通索引:idx_parent_id - 加速查询子评论
  • 普通索引:idx_root_id - 加速查询评论树
  • 普通索引:idx_commenter_id - 加速按用户查询评论

点赞表索引:

  • 主键索引:id - 主键唯一标识
  • 唯一索引:uk_target_user_type - 防止重复点赞
  • 普通索引:idx_target_id - 加速按目标查询点赞
  • 普通索引:idx_user_id - 加速按用户查询点赞

三、实体类设计

3.1 创建Comment实体类

创建 kb-document/src/main/java/com/knowledge/base/document/entity/Comment.java:

package com.knowledge.base.document.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import com.knowledge.base.common.config.BaseEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.time.LocalDateTime;

/**
 * 评论实体
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("tb_comment")
@Schema(description = "评论实体")
public class Comment extends BaseEntity {

    private static final long serialVersionUID = 1L;

    /**
     * 评论ID
     */
    @TableId(type = IdType.ASSIGN_ID)
    @Schema(description = "评论ID")
    private Long id;

    /**
     * 文档ID
     */
    @Schema(description = "文档ID")
    private Long documentId;

    /**
     * 父评论ID
     */
    @Schema(description = "父评论ID")
    private Long parentId;

    /**
     * 根评论ID
     */
    @Schema(description = "根评论ID")
    private Long rootId;

    /**
     * 评论内容
     */
    @Schema(description = "评论内容")
    private String content;

    /**
     * 评论人ID
     */
    @Schema(description = "评论人ID")
    private Long commenterId;

    /**
     * 评论人姓名
     */
    @Schema(description = "评论人姓名")
    private String commenterName;

    /**
     * 评论人头像
     */
    @Schema(description = "评论人头像")
    private String commenterAvatar;

    /**
     * 回复给谁(用户ID)
     */
    @Schema(description = "回复给谁")
    private Long replyToUserId;

    /**
     * 回复给谁(用户姓名)
     */
    @Schema(description = "回复给谁")
    private String replyToUserName;

    /**
     * 状态:0-隐藏,1-正常
     */
    @Schema(description = "状态")
    private Integer status;

    /**
     * 点赞数
     */
    @Schema(description = "点赞数")
    private Integer likeCount;

    /**
     * 回复数
     */
    @Schema(description = "回复数")
    private Integer replyCount;

    /**
     * 创建时间
     */
    @Schema(description = "创建时间")
    private LocalDateTime createdAt;

    /**
     * 更新时间
     */
    @Schema(description = "更新时间")
    private LocalDateTime updatedAt;

    /**
     * 删除标记
     */
    @TableLogic
    @Schema(description = "删除标记")
    private Integer deleted;
}

设计要点:

  • 继承BaseEntity获得通用字段
  • 使用@TableId(type = IdType.ASSIGN_ID)配置雪花ID生成策略
  • 使用@TableLogic配置逻辑删除
  • 冗余存储用户信息(姓名、头像)避免关联查询
  • 冗余存储计数信息(点赞数、回复数)提升查询性能

四、DTO设计

4.1 创建评论DTO

创建 kb-document/src/main/java/com/knowledge/base/document/dto/CommentCreateDTO.java:

package com.knowledge.base.document.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data;

/**
 * 评论创建DTO
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Schema(description = "评论创建请求")
public class CommentCreateDTO {

    @NotNull(message = "文档ID不能为空")
    @Schema(description = "文档ID")
    private Long documentId;

    @Schema(description = "父评论ID")
    private Long parentId;

    @NotBlank(message = "评论内容不能为空")
    @Schema(description = "评论内容")
    private String content;

    @Schema(description = "回复给谁(用户ID)")
    private Long replyToUserId;
}

设计要点:

  • 使用@NotNull和@NotBlank进行参数校验
  • parentId为可选,不传表示创建根评论
  • replyToUserId为可选,用于回复时标识回复对象

4.2 评论查询DTO

创建 kb-document/src/main/java/com/knowledge/base/document/dto/CommentQueryDTO.java:

package com.knowledge.base.document.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

/**
 * 评论查询DTO
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Schema(description = "评论查询请求")
public class CommentQueryDTO {

    @Schema(description = "当前页")
    private Long current = 1L;

    @Schema(description = "每页大小")
    private Long size = 10L;

    @Schema(description = "排序方式:like_count-点赞数,created_at-创建时间")
    private String sortBy = "created_at";

    @Schema(description = "排序方向:asc-升序,desc-降序")
    private String sortOrder = "desc";
}

设计要点:

  • 支持分页查询(current、size)
  • 支持灵活排序(sortBy、sortOrder)
  • 默认按创建时间倒序排列

五、VO设计

5.1 创建评论VO

创建 kb-document/src/main/java/com/knowledge/base/document/vo/CommentVO.java:

package com.knowledge.base.document.vo;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 评论VO
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "评论信息")
public class CommentVO {

    @Schema(description = "评论ID")
    private Long id;

    @Schema(description = "文档ID")
    private Long documentId;

    @Schema(description = "父评论ID")
    private Long parentId;

    @Schema(description = "根评论ID")
    private Long rootId;

    @Schema(description = "评论内容")
    private String content;

    @Schema(description = "评论人ID")
    private Long commenterId;

    @Schema(description = "评论人姓名")
    private String commenterName;

    @Schema(description = "评论人头像")
    private String commenterAvatar;

    @Schema(description = "回复给谁(用户ID)")
    private Long replyToUserId;

    @Schema(description = "回复给谁(用户姓名)")
    private String replyToUserName;

    @Schema(description = "状态")
    private Integer status;

    @Schema(description = "点赞数")
    private Integer likeCount;

    @Schema(description = "回复数")
    private Integer replyCount;

    @Schema(description = "是否已点赞")
    private Boolean isLiked;

    @Schema(description = "创建时间")
    private LocalDateTime createdAt;

    @Schema(description = "子评论列表")
    private List<CommentVO> replies;
}

设计要点:

  • 使用@Builder模式支持灵活构建
  • isLiked字段标识当前用户是否已点赞
  • replies字段支持树形结构展示
  • 包含完整的用户信息用于前端展示

六、Mapper层设计

6.1 创建CommentMapper接口

创建 kb-document/src/main/java/com/knowledge/base/document/mapper/CommentMapper.java:

package com.knowledge.base.document.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.knowledge.base.document.entity.Comment;
import org.apache.ibatis.annotations.Mapper;

/**
 * 评论Mapper接口
 *
 * @author 苏三
 * @since 1.0.0
 */
@Mapper
public interface CommentMapper extends BaseMapper<Comment> {

}

设计要点:

  • 继承BaseMapper<Comment>获得基础CRUD方法
  • 使用@Mapper注解标记为MyBatis Mapper接口
  • 定义了多个查询方法支持评论查询和统计

6.2 创建CommentMapper.xml

创建 kb-document/src/main/resources/mapper/CommentMapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.knowledge.base.document.mapper.CommentMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.knowledge.base.document.entity.Comment">
        <id column="id" property="id" />
        <result column="document_id" property="documentId" />
        <result column="parent_id" property="parentId" />
        <result column="root_id" property="rootId" />
        <result column="content" property="content" />
        <result column="commenter_id" property="commenterId" />
        <result column="commenter_name" property="commenterName" />
        <result column="commenter_avatar" property="commenterAvatar" />
        <result column="reply_to_user_id" property="replyToUserId" />
        <result column="reply_to_user_name" property="replyToUserName" />
        <result column="status" property="status" />
        <result column="like_count" property="likeCount" />
        <result column="reply_count" property="replyCount" />
        <result column="created_at" property="createdAt" />
        <result column="updated_at" property="updatedAt" />
        <result column="deleted" property="deleted" />
        <result column="version" property="version" />
        <result column="create_time" property="createTime" />
        <result column="update_time" property="updateTime" />
        <result column="create_by" property="createBy" />
        <result column="update_by" property="updateBy" />
    </resultMap>
    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, document_id, parent_id, root_id, content, commenter_id, commenter_name, commenter_avatar,
        reply_to_user_id, reply_to_user_name, status, like_count, reply_count, created_at, updated_at,
        deleted, version, create_time, update_time, create_by, update_by
    </sql>
    <!-- 根据文档ID查询评论列表 -->
    <select id="selectByDocumentId" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_comment
        WHERE document_id = #{documentId}
        AND parent_id IS NULL
        AND status = 1
        AND deleted = 0
        ORDER BY created_at DESC
    </select>
    <!-- 根据父评论ID查询回复列表 -->
    <select id="selectByParentId" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_comment
        WHERE parent_id = #{parentId}
        AND status = 1
        AND deleted = 0
        ORDER BY created_at ASC
    </select>
    <!-- 根据评论者ID查询评论列表 -->
    <select id="selectByCommenterId" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_comment
        WHERE commenter_id = #{commenterId}
        AND deleted = 0
        ORDER BY created_at DESC
    </select>
    <!-- 增加点赞数 -->
    <update id="incrementLikeCount">
        UPDATE tb_comment
        SET like_count = like_count + 1
        WHERE id = #{commentId}
        AND deleted = 0
    </update>
    <!-- 减少点赞数 -->
    <update id="decrementLikeCount">
        UPDATE tb_comment
        SET like_count = GREATEST(like_count - 1, 0)
        WHERE id = #{commentId}
        AND deleted = 0
    </update>
    <!-- 增加回复数 -->
    <update id="incrementReplyCount">
        UPDATE tb_comment
        SET reply_count = reply_count + 1
        WHERE id = #{commentId}
        AND deleted = 0
    </update>
    <!-- 更新评论状态 -->
    <update id="updateStatus">
        UPDATE tb_comment
        SET status = #{status}
        WHERE id = #{commentId}
        AND deleted = 0
    </update>
    <!-- 统计文档的评论数量 -->
    <select id="countByDocumentId" resultType="java.lang.Long">
        SELECT COUNT(*)
        FROM tb_comment
        WHERE document_id = #{documentId}
        AND status = 1
        AND deleted = 0
    </select>
</mapper>

Mapper方法说明:

方法说明使用场景
selectByDocumentId查询文档的根评论列表评论列表展示
selectByParentId查询父评论的回复列表子评论展示
selectByCommenterId查询用户的所有评论用户评论历史
incrementLikeCount增加点赞数点赞操作
decrementLikeCount减少点赞数取消点赞
incrementReplyCount增加回复数新增回复
updateStatus更新评论状态评论审核/隐藏
countByDocumentId统计文档评论数评论数统计

七、Service层设计

7.1 创建CommentService接口

创建 kb-document/src/main/java/com/knowledge/base/document/service/CommentService.java:

package com.knowledge.base.document.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.knowledge.base.common.result.PageResult;
import com.knowledge.base.document.dto.CommentCreateDTO;
import com.knowledge.base.document.dto.CommentQueryDTO;
import com.knowledge.base.document.entity.Comment;
import com.knowledge.base.document.vo.CommentVO;

/**
 * 评论Service接口
 *
 * @author 苏三
 * @since 1.0.0
 */
public interface CommentService extends IService<Comment> {

    /**
     * 创建评论
     *
     * @param dto 创建DTO
     * @return 评论ID
     */
    Long createComment(CommentCreateDTO dto);

    /**
     * 删除评论
     *
     * @param commentId 评论ID
     * @return 是否成功
     */
    Boolean deleteComment(Long commentId);

    /**
     * 点赞评论
     *
     * @param commentId 评论ID
     * @return 是否成功
     */
    Boolean likeComment(Long commentId);

    /**
     * 取消点赞评论
     *
     * @param commentId 评论ID
     * @return 是否成功
     */
    Boolean unlikeComment(Long commentId);

    /**
     * 分页查询文档评论
     *
     * @param documentId 文档ID
     * @param dto 查询DTO
     * @return 分页结果
     */
    PageResult<CommentVO> pageDocumentComments(Long documentId, CommentQueryDTO dto);

    /**
     * 获取评论回复列表
     *
     * @param parentCommentId 父评论ID
     * @return 回复列表
     */
    java.util.List<CommentVO> getCommentReplies(Long parentCommentId);
}

7.2 创建CommentServiceImpl实现类

创建 kb-document/src/main/java/com/knowledge/base/document/service/impl/CommentServiceImpl.java:

package com.knowledge.base.document.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.knowledge.base.common.exception.BusinessException;
import com.knowledge.base.common.result.PageResult;
import com.knowledge.base.common.utils.SnowflakeIdGenerator;
import com.knowledge.base.document.dto.CommentCreateDTO;
import com.knowledge.base.document.dto.CommentQueryDTO;
import com.knowledge.base.document.entity.Comment;
import com.knowledge.base.document.mapper.CommentMapper;
import com.knowledge.base.document.service.CommentService;
import com.knowledge.base.document.vo.CommentVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 评论Service实现类
 *
 * <p>按照阿里巴巴Java开发规范设计,实现评论相关业务逻辑</p>
 *
 * @author 苏三
 * @since 1.0.0
 */
@Slf4j
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createComment(CommentCreateDTO dto) {
        log.info("创建评论:documentId={}, parentId={}", dto.getDocumentId(), dto.getParentId());

        // 检查父评论是否存在
        Long rootId = null;
        if (dto.getParentId() != null && dto.getParentId() > 0) {
            Comment parentComment = commentMapper.selectById(dto.getParentId());
            if (parentComment == null) {
                throw new BusinessException("父评论不存在");
            }
            if (!parentComment.getDocumentId().equals(dto.getDocumentId())) {
                throw new BusinessException("父评论不属于该文档");
            }
            rootId = parentComment.getRootId() != null ? parentComment.getRootId() : parentComment.getId();

            // 更新父评论的回复数
            jdbcTemplate.update(
                    "UPDATE tb_comment SET reply_count = reply_count + 1 WHERE id = ?",
                    dto.getParentId()
            );
        }

        // TODO: 从上下文获取当前用户信息
        Long userId = 1L;
        String userName = "测试用户";
        String userAvatar = "/avatar/default.png";

        // 构建评论实体
        Comment comment = new Comment();
        comment.setId(SnowflakeIdGenerator.getInstance().nextId());
        comment.setDocumentId(dto.getDocumentId());
        comment.setParentId(dto.getParentId() != null ? dto.getParentId() : 0L);
        comment.setRootId(rootId);
        comment.setContent(dto.getContent());
        comment.setCommenterId(userId);
        comment.setCommenterName(userName);
        comment.setCommenterAvatar(userAvatar);
        comment.setReplyToUserId(dto.getReplyToUserId());
        comment.setStatus(1);
        comment.setLikeCount(0);
        comment.setReplyCount(0);
        comment.setCreatedAt(LocalDateTime.now());
        comment.setUpdatedAt(LocalDateTime.now());
        comment.setDeleted(0);

        // 保存评论
        int count = commentMapper.insert(comment);
        if (count <= 0) {
            throw new BusinessException("创建评论失败");
        }

        // 更新文档的评论数
        jdbcTemplate.update(
                "UPDATE kb_document SET comment_count = comment_count + 1 WHERE id = ?",
                dto.getDocumentId()
        );

        return comment.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteComment(Long commentId) {
        log.info("删除评论:commentId={}", commentId);

        if (commentId == null) {
            throw new BusinessException("评论ID不能为空");
        }

        // 检查评论是否存在
        Comment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            throw new BusinessException("评论不存在");
        }

        // TODO: 检查权限,只有评论作者或管理员可以删除

        // 检查是否有子评论
        Long childCount = commentMapper.selectCount(
                new LambdaQueryWrapper<Comment>()
                        .eq(Comment::getParentId, commentId)
        );
        if (childCount > 0) {
            throw new BusinessException("该评论下有回复,不能删除");
        }

        // 删除评论
        int count = commentMapper.deleteById(commentId);

        // 更新父评论的回复数
        if (comment.getParentId() != null && comment.getParentId() > 0) {
            jdbcTemplate.update(
                    "UPDATE tb_comment SET reply_count = reply_count - 1 WHERE id = ?",
                    comment.getParentId()
            );
        }

        // 更新文档的评论数
        if (count > 0) {
            jdbcTemplate.update(
                    "UPDATE kb_document SET comment_count = comment_count - 1 WHERE id = ?",
                    comment.getDocumentId()
            );
        }

        return count > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean likeComment(Long commentId) {
        log.info("点赞评论:commentId={}", commentId);

        if (commentId == null) {
            throw new BusinessException("评论ID不能为空");
        }

        // 检查评论是否存在
        Comment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            throw new BusinessException("评论不存在");
        }

        // TODO: 从上下文获取当前用户ID
        Long userId = 1L;

        // 检查是否已点赞
        Integer count = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM tb_like WHERE target_id = ? AND user_id = ? AND target_type = 2",
                Integer.class,
                commentId, userId
        );

        if (count != null && count > 0) {
            throw new BusinessException("已经点赞过了");
        }

        // 添加点赞记录
        jdbcTemplate.update(
                "INSERT INTO tb_like (id, target_id, user_id, target_type, created_at) VALUES (?, ?, ?, 2, NOW())",
                SnowflakeIdGenerator.getInstance().nextId(), commentId, userId
        );

        // 更新评论点赞数
        jdbcTemplate.update(
                "UPDATE tb_comment SET like_count = like_count + 1 WHERE id = ?",
                commentId
        );

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean unlikeComment(Long commentId) {
        log.info("取消点赞评论:commentId={}", commentId);

        if (commentId == null) {
            throw new BusinessException("评论ID不能为空");
        }

        // 检查评论是否存在
        Comment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            throw new BusinessException("评论不存在");
        }

        // TODO: 从上下文获取当前用户ID
        Long userId = 1L;

        // 删除点赞记录
        int count = jdbcTemplate.update(
                "DELETE FROM tb_like WHERE target_id = ? AND user_id = ? AND target_type = 2",
                commentId, userId
        );

        // 更新评论点赞数
        if (count > 0) {
            jdbcTemplate.update(
                    "UPDATE tb_comment SET like_count = like_count - 1 WHERE id = ?",
                    commentId
            );
        }

        return count > 0;
    }

    @Override
    public PageResult<CommentVO> pageDocumentComments(Long documentId, CommentQueryDTO dto) {
        // 构建查询条件 - 只查询根评论
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getDocumentId, documentId)
                .eq(Comment::getParentId, 0)
                .eq(Comment::getStatus, 1);

        // 排序
        if (StringUtils.hasText(dto.getSortBy())) {
            if ("like_count".equals(dto.getSortBy())) {
                wrapper.orderByDesc(Comment::getLikeCount);
            } else {
                boolean isAsc = "asc".equals(dto.getSortOrder());
                if (isAsc) {
                    wrapper.orderByAsc(Comment::getCreatedAt);
                } else {
                    wrapper.orderByDesc(Comment::getCreatedAt);
                }
            }
        } else {
            wrapper.orderByDesc(Comment::getCreatedAt);
        }

        // 分页查询
        Page<Comment> page = new Page<>(dto.getCurrent(), dto.getSize());
        IPage<Comment> commentPage = commentMapper.selectPage(page, wrapper);

        // 转换为VO并加载子评论
        IPage<CommentVO> voPage = commentPage.convert(comment -> {
            CommentVO vo = convertToVO(comment);
            // TODO: 设置是否已点赞
            vo.setIsLiked(false);
            // 加载子评论
            vo.setReplies(getCommentReplies(comment.getId()));
            return vo;
        });

        return PageResult.<CommentVO>builder()
                .records(voPage.getRecords())
                .total(voPage.getTotal())
                .current(voPage.getCurrent())
                .size(voPage.getSize())
                .build();
    }

    @Override
    public List<CommentVO> getCommentReplies(Long parentCommentId) {
        if (parentCommentId == null || parentCommentId <= 0) {
            return new ArrayList<>();
        }

        List<Comment> comments = commentMapper.selectList(
                new LambdaQueryWrapper<Comment>()
                        .eq(Comment::getParentId, parentCommentId)
                        .eq(Comment::getStatus, 1)
                        .orderByAsc(Comment::getCreatedAt)
        );

        return comments.stream()
                .map(comment -> {
                    CommentVO vo = convertToVO(comment);
                    // TODO: 设置是否已点赞
                    vo.setIsLiked(false);
                    return vo;
                })
                .collect(Collectors.toList());
    }

    /**
     * 转换为VO
     *
     * @param comment 评论实体
     * @return 评论VO
     */
    private CommentVO convertToVO(Comment comment) {
        return CommentVO.builder()
                .id(comment.getId())
                .documentId(comment.getDocumentId())
                .parentId(comment.getParentId())
                .rootId(comment.getRootId())
                .content(comment.getContent())
                .commenterId(comment.getCommenterId())
                .commenterName(comment.getCommenterName())
                .commenterAvatar(comment.getCommenterAvatar())
                .replyToUserId(comment.getReplyToUserId())
                .replyToUserName(comment.getReplyToUserName())
                .status(comment.getStatus())
                .likeCount(comment.getLikeCount() != null ? comment.getLikeCount() : 0)
                .replyCount(comment.getReplyCount() != null ? comment.getReplyCount() : 0)
                .createdAt(comment.getCreatedAt())
                .build();
    }
}

核心实现要点:

  1. 创建评论逻辑:

    • 验证父评论存在性及归属

      • 自动计算rootId(父评论的rootId或父评论自己的ID)
      • 使用数据库原子操作更新回复数
      • 同步更新文档的评论总数
  2. 删除评论逻辑:

    • 检查是否有子评论,有则不能删除

      • 级联更新父评论的回复数
      • 级联更新文档的评论总数
  3. 点赞逻辑:

    • 先检查是否已点赞,防止重复点赞

      • 插入点赞记录
      • 原子操作更新点赞数
  4. 查询逻辑:

    • 只查询根评论(parentId=0)

      • 支持按点赞数或创建时间排序
      • 自动加载子评论形成树形结构

八、Controller层设计

8.1 创建CommentController

创建 kb-document/src/main/java/com/knowledge/base/document/controller/CommentController.java:

package com.knowledge.base.document.controller;

import com.knowledge.base.common.annotation.OperationLog;
import com.knowledge.base.common.result.PageResult;
import com.knowledge.base.common.result.Result;
import com.knowledge.base.document.dto.CommentCreateDTO;
import com.knowledge.base.document.dto.CommentQueryDTO;
import com.knowledge.base.document.service.CommentService;
import com.knowledge.base.document.vo.CommentVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 评论管理Controller
 *
 * @author 苏三
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/api/comments")
@RequiredArgsConstructor
@Tag(name = "评论管理", description = "评论管理相关接口")
public class CommentController {

    private final CommentService commentService;

    /**
     * 创建评论
     */
    @PostMapping
    @Operation(summary = "创建评论", description = "创建文档评论")
    @OperationLog(module = "评论管理", operation = "创建评论", description = "创建文档评论")
    public Result<Long> createComment(@Valid @RequestBody CommentCreateDTO dto) {
        Long commentId = commentService.createComment(dto);
        return Result.success(commentId);
    }

    /**
     * 删除评论
     */
    @DeleteMapping("/{commentId}")
    @Operation(summary = "删除评论", description = "删除指定评论")
    @OperationLog(module = "评论管理", operation = "删除评论", description = "删除评论")
    public Result<Boolean> deleteComment(@PathVariable Long commentId) {
        Boolean result = commentService.deleteComment(commentId);
        return Result.success(result);
    }

    /**
     * 点赞评论
     */
    @PostMapping("/{commentId}/like")
    @Operation(summary = "点赞评论", description = "点赞指定评论")
    @OperationLog(module = "评论管理", operation = "点赞评论", description = "点赞评论")
    public Result<Boolean> likeComment(@PathVariable Long commentId) {
        Boolean result = commentService.likeComment(commentId);
        return Result.success(result);
    }

    /**
     * 取消点赞评论
     */
    @DeleteMapping("/{commentId}/like")
    @Operation(summary = "取消点赞评论", description = "取消点赞评论")
    @OperationLog(module = "评论管理", operation = "取消点赞", description = "取消点赞评论")
    public Result<Boolean> unlikeComment(@PathVariable Long commentId) {
        Boolean result = commentService.unlikeComment(commentId);
        return Result.success(result);
    }

    /**
     * 分页查询文档评论
     */
    @PostMapping("/document/{documentId}")
    @Operation(summary = "分页查询文档评论", description = "分页查询文档评论列表")
    public Result<PageResult<CommentVO>> pageDocumentComments(
            @PathVariable Long documentId,
            @RequestBody CommentQueryDTO dto) {
        PageResult<CommentVO> pageResult = commentService.pageDocumentComments(documentId, dto);
        return Result.success(pageResult);
    }

    /**
     * 获取评论回复列表
     */
    @GetMapping("/{parentCommentId}/replies")
    @Operation(summary = "获取评论回复", description = "获取评论的回复列表")
    public Result<List<CommentVO>> getCommentReplies(@PathVariable Long parentCommentId) {
        List<CommentVO> replies = commentService.getCommentReplies(parentCommentId);
        return Result.success(replies);
    }
}

接口设计要点:

  1. 创建评论 - POST /api/comments

    • 支持创建根评论和回复评论

      • 通过parentId区分
  2. 删除评论 - DELETE /api/comments/{commentId}

    • 删除前检查是否有子评论
  3. 点赞评论 - POST /api/comments/{commentId}/like

    • 防止重复点赞
  4. 取消点赞 - DELETE /api/comments/{commentId}/like

    • 删除点赞记录并更新计数
  5. 分页查询 - POST /api/comments/document/{documentId}

    • 只返回根评论

      • 子评论通过replies字段返回
  6. 获取回复 - GET /api/comments/{parentCommentId}/replies

    • 返回指定评论的所有子评论

九、测试验证

9.1 启动应用

# 启动kb-document服务
cd kb-document
mvn spring-boot:run

9.2 测试创建评论

创建根评论:

curl -X POST 'http://localhost:8083/api/comments' \
  -H 'Content-Type: application/json' \
  -d '{
    "documentId": 1,
    "content": "这篇文档写得真好!"
  }'

创建回复评论:

curl -X POST 'http://localhost:8083/api/comments' \
  -H 'Content-Type: application/json' \
  -d '{
    "documentId": 1,
    "parentId": 1,
    "content": "确实很有帮助!",
    "replyToUserId": 1
  }'

9.3 测试查询评论

分页查询文档评论:

curl -X POST 'http://localhost:8083/api/comments/document/1' \
  -H 'Content-Type: application/json' \
  -d '{
    "current": 1,
    "size": 10,
    "sortBy": "like_count",
    "sortOrder": "desc"
  }'

获取评论回复:

curl -X GET 'http://localhost:8083/api/comments/1/replies'

9.4 测试点赞功能

点赞评论:

curl -X POST 'http://localhost:8083/api/comments/1/like'

取消点赞:

9.5 测试删除评论

curl -X DELETE 'http://localhost:8083/api/comments/1'

9.6 验证 Knife4j 文档

访问:http://localhost:8083/doc.html

查看评论管理相关接口的API文档和在线测试。

总结

本文详细介绍了kb-document服务中评论相关功能的完整实现,包括:

核心功能

  • ✅ 评论创建(支持根评论和回复)
  • ✅ 评论删除(带子评论检查)
  • ✅ 点赞/取消点赞(防重复)
  • ✅ 分页查询(支持排序)
  • ✅ 评论树形结构展示
最后修改:2026 年 10 月 24 日
如果觉得我的文章对你有用,请随意赞赏