一、概述
文档评价功能是知识库系统用户互动的核心模块,涵盖文档点赞、文档收藏和评论点赞三大功能。
通过这些互动机制,用户可以对文档质量进行评价,收藏感兴趣的文档以便随时查阅,并与其他用户展开讨论。
1.1 功能定位
| 功能模块 | 说明 | 使用场景 |
|---|---|---|
| 文档点赞 | 对文档点赞/取消点赞 | 表达对文档的认可 |
| 文档收藏 | 收藏/取消收藏文档 | 保存感兴趣的文档,方便后续查看 |
| 评论点赞 | 对评论点赞/取消点赞 | 认可有价值的评论 |
| 浏览统计 | 记录文档浏览次数 | 数据统计和热度排行 |
1.2 数据模型
评价功能涉及多张数据表,关系如下:
┌─────────────┐ ┌──────────────┐ ┌──────────────────┐
│ kb_document │────→│ tb_like │←────│ tb_comment │
│ │ │ │ │ │
│ like_count │ │ target_id │ │ like_count │
│ fav_count │ │ target_type │ │ reply_count │
│ view_count │ │ user_id │ │ │
└──────┬──────┘ └──────────────┘ └──────────────────┘
│
│ ┌──────────────────┐
└──────────────→│ kb_user_favorite │
│ │
│ user_id │
│ document_id │
└──────────────────┘1.3 技术要点
- 点赞表统一设计:
tb_like通过target_type字段区分文档点赞(type=1)和评论点赞(type=2),避免多张点赞表 - 唯一约束防重:
uk_target_user_type唯一索引防止同一用户重复点赞 - 计数冗余:
like_count冗余存储在文档和评论表中,避免每次查询都需要 JOIN - 物理删除 vs 逻辑删除:收藏记录使用物理删除(避免唯一约束冲突),点赞记录也使用物理删除
- 乐观更新:前端先更新本地状态,再发API请求,提升用户感知速度
二、数据库设计
2.1 统一点赞表
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.2 用户收藏表
DROP TABLE IF EXISTS `kb_user_favorite`;
CREATE TABLE `kb_user_favorite` (
`id` BIGINT NOT NULL COMMENT '收藏ID',
`user_id` BIGINT NOT NULL COMMENT '用户ID',
`document_id` BIGINT NOT NULL COMMENT '文档ID',
`document_title` VARCHAR(200) DEFAULT NULL COMMENT '文档标题(冗余字段)',
`document_category_id` BIGINT DEFAULT NULL COMMENT '文档分类ID(冗余字段)',
`favorite_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '收藏时间',
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`deleted` TINYINT NOT NULL DEFAULT 0 COMMENT '删除标识',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_user_document` (`user_id`, `document_id`, `deleted`),
KEY `idx_user_id` (`user_id`),
KEY `idx_document_id` (`document_id`),
KEY `idx_favorite_time` (`favorite_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户收藏表';2.3 为文档表添加计数器字段
在 kb_document 表中添加计数字段:
ALTER TABLE `kb_document`
ADD COLUMN `like_count` BIGINT DEFAULT 0 COMMENT '点赞数',
ADD COLUMN `favorite_count` BIGINT DEFAULT 0 COMMENT '收藏数',
ADD COLUMN `comment_count` BIGINT DEFAULT 0 COMMENT '评论数';2.4 为评论表添加点赞计数字段
在 tb_comment 表中已有 like_count 字段:
-- 评论表中的点赞计数字段(建表时已包含)
`like_count` INT DEFAULT 0 COMMENT '点赞数',2.5 字段说明
tb\_like 表:
| 字段 | 类型 | 说明 | 必填 |
|---|---|---|---|
| id | BIGINT | 点赞ID(雪花算法) | 是 |
| target\_id | BIGINT | 目标ID | 是 |
| target\_type | TINYINT | 1=文档,2=评论 | 是 |
| user\_id | BIGINT | 用户ID | 是 |
kb\_user\_favorite 表:
| 字段 | 类型 | 说明 | 必填 |
|---|---|---|---|
| id | BIGINT | 收藏ID | 是 |
| user\_id | BIGINT | 用户ID | 是 |
| document\_id | BIGINT | 文档ID | 是 |
| document\_title | VARCHAR(200) | 文档标题(冗余) | 否 |
| document\_category\_id | BIGINT | 分类ID(冗余) | 否 |
| favorite\_time | DATETIME | 收藏时间 | 是 |
2.6 索引设计
uk_target_user_type:点赞唯一索引,防止重复点赞uk_user_document:收藏唯一索引(联合 deleted),防止重复收藏idx_user_id:加速按用户查询点赞/收藏记录idx_target_id:加速按目标查询点赞记录
三、实体类设计
3.1 Document 实体 - 添加计数字段
在 Document.java 中添加以下字段:
/**
* 浏览数量
*/
private Long viewCount;
/**
* 点赞数量
*/
private Long likeCount;
/**
* 收藏数量
*/
private Long favoriteCount;
/**
* 评论数量
*/
private Long commentCount;3.2 Comment 实体 - 点赞计数字段
在 Comment.java 中已有:
/**
* 点赞数
*/
private Integer likeCount;
/**
* 回复数
*/
private Integer replyCount;3.3 UserFavorite 实体
创建 kb-document/src/main/java/com/knowledge/base/document/entity/UserFavorite.java:
package com.knowledge.base.document.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import com.knowledge.base.common.config.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
/**
* 用户收藏实体类
*
* @author 苏三
* @since 1.0.0
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("kb_user_favorite")
public class UserFavorite extends BaseEntity {
/**
* 重写 deleted 字段,支持逻辑删除
* 收藏功能在切换状态时使用物理删除以避免唯一约束问题
*/
@TableLogic(value = "0", delval = "1")
private Integer deleted;
/** 用户ID */
private Long userId;
/** 文档ID */
private Long documentId;
/** 文档标题(冗余字段,避免每次查询 JOIN) */
private String documentTitle;
/** 文档分类ID(冗余字段) */
private Long documentCategoryId;
/** 收藏时间 */
private LocalDateTime favoriteTime;
// 以下为关联查询字段,不存储在数据库中
@TableField(exist = false)
private String documentSummary;
@TableField(exist = false)
private String documentAuthorName;
@TableField(exist = false)
private Long documentAuthorId;
@TableField(exist = false)
private Integer documentStatus;
@TableField(exist = false)
private Long documentViewCount;
}3.4 设计思路
- 冗余字段:
documentTitle、documentCategoryId冗余存储,避免收藏列表页每次都要 JOIN 文档表 - 关联字段:
@TableField(exist = false)标注的字段仅用于 VO 组装,不存入数据库 - 物理删除:取消收藏时使用物理删除而非逻辑删除,因为唯一约束
uk_user_document联合了deleted字段,逻辑删除后再收藏会导致唯一约束冲突
四、DTO 和 VO 设计
4.1 FavoriteDTO
创建 kb-document/src/main/java/com/knowledge/base/document/dto/FavoriteDTO.java:
package com.knowledge.base.document.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.io.Serializable;
@Data
@Schema(description = "收藏操作请求参数")
public class FavoriteDTO implements Serializable {
@NotNull(message = "文档ID不能为空")
@Schema(description = "文档ID")
private Long documentId;
@Schema(description = "操作类型:add-添加收藏,remove-取消收藏")
private String action;
}4.2 UserFavoriteVO
创建 kb-document/src/main/java/com/knowledge/base/document/vo/UserFavoriteVO.java:
package com.knowledge.base.document.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@Schema(description = "用户收藏信息")
public class UserFavoriteVO implements Serializable {
@Schema(description = "收藏记录ID")
private Long id;
@Schema(description = "用户ID")
private Long userId;
@Schema(description = "文档ID")
private Long documentId;
@Schema(description = "文档标题")
private String documentTitle;
@Schema(description = "文档摘要")
private String documentSummary;
@Schema(description = "文档分类ID")
private Long documentCategoryId;
@Schema(description = "文档分类名称")
private String documentCategoryName;
@Schema(description = "文档作者ID")
private Long documentAuthorId;
@Schema(description = "文档作者名称")
private String documentAuthorName;
@Schema(description = "文档状态")
private Integer documentStatus;
@Schema(description = "文档浏览次数")
private Long documentViewCount;
@Schema(description = "收藏时间")
private LocalDateTime favoriteTime;
@Schema(description = "是否已收藏")
private Boolean isFavorited;
}4.3 DocumentVO - 添加点赞状态字段
在 DocumentVO.java 中已有 isLiked 字段(前端用于渲染当前用户的点赞状态):
@Schema(description = "当前用户是否已点赞")
private Boolean isLiked;4.4 CommentVO - 添加点赞状态字段
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CommentVO {
// ... 基础字段
@Schema(description = "点赞数")
private Integer likeCount;
@Schema(description = "当前用户是否已点赞")
private Boolean isLiked;
}五、数据访问层
5.1 DocumentMapper - 添加计数操作
在 DocumentMapper.java 中添加以下方法声明:
/**
* 增加浏览数量
*/
int incrementViewCount(@Param("documentId") Long documentId);
/**
* 增加点赞数量
*/
int incrementLikeCount(@Param("documentId") Long documentId);
/**
* 减少点赞数量
*/
int decrementLikeCount(@Param("documentId") Long documentId);
/**
* 增加收藏数量
*/
int incrementFavoriteCount(@Param("documentId") Long documentId);
/**
* 减少收藏数量
*/
int decrementFavoriteCount(@Param("documentId") Long documentId);
/**
* 增加评论数量
*/
int incrementCommentCount(@Param("documentId") Long documentId);在 DocumentMapper.xml 中添加对应 SQL:
<!-- 增加浏览次数 -->
<update id="incrementViewCount">
UPDATE kb_document
SET view_count = view_count + 1
WHERE id = #{documentId} AND deleted = 0
</update>
<!-- 增加点赞次数 -->
<update id="incrementLikeCount">
UPDATE kb_document
SET like_count = like_count + 1
WHERE id = #{documentId} AND deleted = 0
</update>
<!-- 减少点赞次数 -->
<update id="decrementLikeCount">
UPDATE kb_document
SET like_count = GREATEST(like_count - 1, 0)
WHERE id = #{documentId} AND deleted = 0
</update>
<!-- 增加收藏次数 -->
<update id="incrementFavoriteCount">
UPDATE kb_document
SET favorite_count = favorite_count + 1
WHERE id = #{documentId} AND deleted = 0
</update>
<!-- 减少收藏次数 -->
<update id="decrementFavoriteCount">
UPDATE kb_document
SET favorite_count = GREATEST(favorite_count - 1, 0)
WHERE id = #{documentId} AND deleted = 0
</update>
<!-- 增加评论次数 -->
<update id="incrementCommentCount">
UPDATE kb_document
SET comment_count = comment_count + 1
WHERE id = #{documentId} AND deleted = 0
</update>注意:使用 GREATEST(col - 1, 0) 保证计数器不会变成负数。5.2 UserFavoriteMapper
创建 kb-document/src/main/java/com/knowledge/base/document/mapper/UserFavoriteMapper.java:
package com.knowledge.base.document.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.knowledge.base.document.entity.UserFavorite;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserFavoriteMapper extends BaseMapper<UserFavorite> {
/**
* 查询用户的收藏列表(LEFT JOIN kb_document 获取文档详情)
*/
@Select("SELECT uf.id, uf.user_id, uf.document_id, uf.document_title, " +
"uf.document_category_id, uf.favorite_time, " +
"d.summary as document_summary, d.author_id as document_author_id, " +
"d.author_name as document_author_name, " +
"d.status as document_status, d.view_count as document_view_count " +
"FROM kb_user_favorite uf " +
"LEFT JOIN kb_document d ON uf.document_id = d.id " +
"WHERE uf.user_id = #{userId} AND uf.deleted = 0 " +
"ORDER BY uf.favorite_time DESC")
List<UserFavorite> getUserFavorites(@Param("userId") Long userId);
/**
* 检查用户是否收藏了指定文档
*/
@Select("SELECT * FROM kb_user_favorite " +
"WHERE user_id = #{userId} AND document_id = #{documentId} " +
"AND deleted = 0 LIMIT 1")
UserFavorite findByUserAndDocument(@Param("userId") Long userId,
@Param("documentId") Long documentId);
/**
* 统计文档收藏数量
*/
@Select("SELECT COUNT(*) FROM kb_user_favorite " +
"WHERE document_id = #{documentId} AND deleted = 0")
Integer countByDocumentId(@Param("documentId") Long documentId);
/**
* 物理删除收藏记录(取消收藏时使用,避免唯一约束冲突)
*/
@Delete("DELETE FROM kb_user_favorite " +
"WHERE user_id = #{userId} AND document_id = #{documentId}")
int physicalDelete(@Param("userId") Long userId,
@Param("documentId") Long documentId);
}5.3 CommentMapper - 点赞操作
在 CommentMapper.java 和 CommentMapper.xml 中添加:
// Mapper 接口
int incrementLikeCount(@Param("commentId") Long commentId);
int decrementLikeCount(@Param("commentId") Long commentId);<!-- Mapper XML -->
<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>六、业务逻辑层
6.1 文档点赞/取消点赞
在 DocumentServiceImpl.java 中实现:
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean likeDocument(Long documentId) {
log.info("点赞文档:documentId={}", documentId);
if (documentId == null) {
throw new BusinessException("文档ID不能为空");
}
// 检查文档是否存在
Document document = documentMapper.selectById(documentId);
if (document == null) {
throw new BusinessException(ResultCode.DOCUMENT_NOT_EXIST);
}
Long userId = UserContext.getCurrentUserId();
// 检查是否已点赞(target_type = 1 表示文档)
Integer count = jdbcTemplate.queryForObject(
"SELECT COUNT(*) FROM tb_like WHERE target_id = ? "
+ "AND user_id = ? AND target_type = 1",
Integer.class, documentId, userId);
if (count != null && count > 0) {
throw new BusinessException("已经点赞过了");
}
// 1. 添加点赞记录
jdbcTemplate.update(
"INSERT INTO tb_like (id, target_id, user_id, target_type, created_at) "
+ "VALUES (?, ?, ?, 1, NOW())",
SnowflakeIdGenerator.getInstance().nextId(), documentId, userId);
// 2. 增加文档点赞计数
int updated = documentMapper.incrementLikeCount(documentId);
return updated > 0;
}
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean unlikeDocument(Long documentId) {
log.info("取消点赞文档:documentId={}", documentId);
if (documentId == null) {
throw new BusinessException("文档ID不能为空");
}
// 检查文档是否存在
Document document = documentMapper.selectById(documentId);
if (document == null) {
throw new BusinessException(ResultCode.DOCUMENT_NOT_EXIST);
}
Long userId = UserContext.getCurrentUserId();
// 1. 删除点赞记录(物理删除)
int count = jdbcTemplate.update(
"DELETE FROM tb_like WHERE target_id = ? "
+ "AND user_id = ? AND target_type = 1",
documentId, userId);
// 2. 减少文档点赞计数
if (count > 0) {
documentMapper.decrementLikeCount(documentId);
}
return count > 0;
}核心逻辑:
- 点赞流程:验证文档存在 → 检查是否已点赞 → 插入
tb_like记录 → 递增kb_document.like_count - 取消点赞流程:验证文档存在 → 物理删除
tb_like记录 → 递减kb_document.like_count - 事务处理:使用
@Transactional保证点赞记录和计数更新的一致性
6.2 文档收藏/取消收藏
6.2.1 Service 接口
创建 kb-document/src/main/java/com/knowledge/base/document/service/UserFavoriteService.java:
package com.knowledge.base.document.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.knowledge.base.document.entity.UserFavorite;
import com.knowledge.base.document.vo.UserFavoriteVO;
import java.util.List;
public interface UserFavoriteService extends IService<UserFavorite> {
/** 添加收藏 */
Boolean addFavorite(Long userId, Long documentId);
/** 取消收藏 */
Boolean removeFavorite(Long userId, Long documentId);
/** 检查是否已收藏 */
Boolean isFavorited(Long userId, Long documentId);
/** 获取用户收藏列表 */
List<UserFavoriteVO> getUserFavorites(Long userId);
/** 获取文档收藏数量 */
Long getFavoriteCount(Long documentId);
/** 切换收藏状态 */
Boolean toggleFavorite(Long userId, Long documentId);
}6.2.2 Service 实现
创建 kb-document/src/main/java/com/knowledge/base/document/service/impl/UserFavoriteServiceImpl.java:
package com.knowledge.base.document.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.knowledge.base.common.exception.BusinessException;
import com.knowledge.base.common.utils.SnowflakeIdGenerator;
import com.knowledge.base.document.entity.Document;
import com.knowledge.base.document.entity.UserFavorite;
import com.knowledge.base.document.mapper.DocumentMapper;
import com.knowledge.base.document.mapper.UserFavoriteMapper;
import com.knowledge.base.document.service.UserFavoriteService;
import com.knowledge.base.document.vo.UserFavoriteVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class UserFavoriteServiceImpl
extends ServiceImpl<UserFavoriteMapper, UserFavorite>
implements UserFavoriteService {
@Resource
private UserFavoriteMapper userFavoriteMapper;
@Resource
private DocumentMapper documentMapper;
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean addFavorite(Long userId, Long documentId) {
// 验证文档是否存在
Document document = documentMapper.selectById(documentId);
if (document == null) {
throw new BusinessException("文档不存在");
}
// 检查是否已收藏
UserFavorite existing = userFavoriteMapper
.findByUserAndDocument(userId, documentId);
if (existing != null) {
return true; // 已收藏,幂等返回成功
}
// 创建收藏记录
UserFavorite favorite = new UserFavorite();
favorite.setId(SnowflakeIdGenerator.getInstance().nextId());
favorite.setUserId(userId);
favorite.setDocumentId(documentId);
favorite.setDocumentTitle(document.getTitle());
favorite.setDocumentCategoryId(document.getCategoryId());
int count = userFavoriteMapper.insert(favorite);
if (count > 0) {
documentMapper.incrementFavoriteCount(documentId);
return true;
}
return false;
}
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean removeFavorite(Long userId, Long documentId) {
// 物理删除,避免唯一约束冲突
int count = userFavoriteMapper.physicalDelete(userId, documentId);
if (count > 0) {
documentMapper.decrementFavoriteCount(documentId);
return true;
}
return false;
}
@Override
public Boolean isFavorited(Long userId, Long documentId) {
UserFavorite favorite = userFavoriteMapper
.findByUserAndDocument(userId, documentId);
return favorite != null;
}
@Override
public List<UserFavoriteVO> getUserFavorites(Long userId) {
List<UserFavorite> favorites = userFavoriteMapper.getUserFavorites(userId);
List<UserFavoriteVO> result = new ArrayList<>();
for (UserFavorite favorite : favorites) {
UserFavoriteVO vo = new UserFavoriteVO();
vo.setId(favorite.getId());
vo.setUserId(favorite.getUserId());
vo.setDocumentId(favorite.getDocumentId());
vo.setDocumentTitle(favorite.getDocumentTitle());
vo.setDocumentSummary(favorite.getDocumentSummary());
vo.setDocumentCategoryId(favorite.getDocumentCategoryId());
vo.setDocumentAuthorName(favorite.getDocumentAuthorName());
vo.setFavoriteTime(favorite.getFavoriteTime());
result.add(vo);
}
return result;
}
@Override
public Long getFavoriteCount(Long documentId) {
Integer count = userFavoriteMapper.countByDocumentId(documentId);
return count != null ? count.longValue() : 0L;
}
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean toggleFavorite(Long userId, Long documentId) {
boolean isFavorited = isFavorited(userId, documentId);
if (isFavorited) {
removeFavorite(userId, documentId);
return false; // 新状态 = 未收藏
} else {
addFavorite(userId, documentId);
return true; // 新状态 = 已收藏
}
}
}核心逻辑:
- 添加收藏:验证文档存在 → 检查是否已收藏(幂等) → 创建收藏记录(含冗余字段) → 递增文档收藏数
- 取消收藏:物理删除收藏记录 → 递减文档收藏数
- 切换收藏:先检查当前状态,再决定添加或取消,返回新状态给前端
6.3 评论点赞/取消点赞
在 CommentServiceImpl.java 中实现:
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean likeComment(Long commentId) {
// 1. 验证评论存在
Comment comment = commentMapper.selectById(commentId);
if (comment == null) {
throw new BusinessException("评论不存在");
}
Long userId = getCurrentUserIdSafely();
// 2. 检查是否已点赞(target_type = 2 表示评论)
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("已经点赞过了");
}
// 3. 插入点赞记录
jdbcTemplate.update(
"INSERT INTO tb_like (id, target_id, user_id, target_type, created_at) "
+ "VALUES (?, ?, ?, 2, NOW())",
SnowflakeIdGenerator.getInstance().nextId(), commentId, userId);
// 4. 递增评论点赞计数
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) {
// 1. 验证评论存在
Comment comment = commentMapper.selectById(commentId);
if (comment == null) {
throw new BusinessException("评论不存在");
}
Long userId = getCurrentUserIdSafely();
// 2. 物理删除点赞记录
int count = jdbcTemplate.update(
"DELETE FROM tb_like WHERE target_id = ? "
+ "AND user_id = ? AND target_type = 2",
commentId, userId);
// 3. 递减评论点赞计数
if (count > 0) {
jdbcTemplate.update(
"UPDATE tb_comment SET like_count = like_count - 1 WHERE id = ?",
commentId);
}
return count > 0;
}与文档点赞的区别:
| 对比项 | 文档点赞 | 评论点赞 |
|---|---|---|
| target\_type | 1 | 2 |
| 计数器位置 | kb\_document.like\_count | tb\_comment.like\_count |
| 计数器更新 | 通过 MyBatis Mapper | 通过 JdbcTemplate |
6.4 批量查询点赞状态
在加载评论列表时,需要标记当前用户对每条评论的点赞状态:
/**
* 批量查询当前用户已点赞的评论ID集合
*/
private Set<Long> queryLikedCommentIds(Long userId, Set<Long> commentIds) {
if (userId == null || commentIds.isEmpty()) {
return Collections.emptySet();
}
String placeholders = commentIds.stream()
.map(id -> "?").collect(Collectors.joining(","));
List<Object> params = new ArrayList<>();
params.add(userId);
params.addAll(commentIds);
List<Long> likedIds = jdbcTemplate.queryForList(
"SELECT target_id FROM tb_like "
+ "WHERE user_id = ? AND target_type = 2 "
+ "AND target_id IN (" + placeholders + ")",
Long.class, params.toArray());
return new HashSet<>(likedIds);
}在分页查询评论和查询回复时调用此方法,设置 commentVO.setLiked(likedIds.contains(comment.getId()))。
6.5 文档浏览统计
@Override
public DocumentVO viewDocument(Long documentId) {
// 增加浏览次数
documentMapper.incrementViewCount(documentId);
// 加载文档内容和作者信息
Document document = documentMapper.selectById(documentId);
if (document == null) {
throw new BusinessException(ResultCode.DOCUMENT_NOT_EXIST);
}
DocumentVO vo = BeanUtil.copyProperties(document, DocumentVO.class);
vo.setAuthor(buildAuthorVO(document.getAuthorId(), document.getAuthorName()));
return vo;
}七、控制器层
7.1 DocumentController - 点赞相关端点
/**
* 点赞文档
*/
@PostMapping("/{documentId}/like")
@Operation(summary = "点赞文档", description = "用户点赞文档")
public Result<Boolean> likeDocument(
@Parameter(description = "文档ID", required = true)
@PathVariable Long documentId) {
Boolean success = documentService.likeDocument(documentId);
return Result.success("点赞成功", success);
}
/**
* 取消点赞文档
*/
@DeleteMapping("/{documentId}/like")
@Operation(summary = "取消点赞文档", description = "用户取消点赞文档")
public Result<Boolean> unlikeDocument(
@Parameter(description = "文档ID", required = true)
@PathVariable Long documentId) {
Boolean success = documentService.unlikeDocument(documentId);
return Result.success("取消点赞成功", success);
}7.2 UserFavoriteController - 收藏端点
创建 kb-document/src/main/java/com/knowledge/base/document/controller/UserFavoriteController.java:
@Slf4j
@RestController
@RequestMapping("/favorite")
@Tag(name = "用户收藏", description = "用户收藏管理接口")
public class UserFavoriteController {
@Resource
private UserFavoriteService userFavoriteService;
@PostMapping("/toggle/{documentId}")
@Operation(summary = "切换收藏状态", description = "切换文档的收藏状态")
public Result<Boolean> toggleFavorite(@PathVariable Long documentId) {
Long userId = UserContext.getCurrentUserId();
Boolean isFavorited = userFavoriteService.toggleFavorite(userId, documentId);
return Result.success(isFavorited);
}
@PostMapping("/add/{documentId}")
@Operation(summary = "添加收藏", description = "添加文档到收藏")
public Result<Boolean> addFavorite(@PathVariable Long documentId) {
Long userId = UserContext.getCurrentUserId();
Boolean result = userFavoriteService.addFavorite(userId, documentId);
return Result.success("添加收藏成功", result);
}
@DeleteMapping("/remove/{documentId}")
@Operation(summary = "取消收藏", description = "取消文档收藏")
public Result<Boolean> removeFavorite(@PathVariable Long documentId) {
Long userId = UserContext.getCurrentUserId();
Boolean result = userFavoriteService.removeFavorite(userId, documentId);
return Result.success("取消收藏成功", result);
}
@GetMapping("/check/{documentId}")
@Operation(summary = "检查收藏状态", description = "检查文档是否已被收藏")
public Result<Boolean> checkFavorite(@PathVariable Long documentId) {
Long userId = UserContext.getCurrentUserId();
Boolean isFavorited = userFavoriteService.isFavorited(userId, documentId);
return Result.success(isFavorited);
}
@GetMapping("/list")
@Operation(summary = "获取收藏列表", description = "获取当前用户的收藏列表")
public Result<List<UserFavoriteVO>> getUserFavorites() {
Long userId = UserContext.getCurrentUserId();
List<UserFavoriteVO> favorites = userFavoriteService.getUserFavorites(userId);
return Result.success(favorites);
}
@GetMapping("/count/{documentId}")
@Operation(summary = "获取收藏数量", description = "获取文档的收藏数量")
public Result<Long> getFavoriteCount(@PathVariable Long documentId) {
Long count = userFavoriteService.getFavoriteCount(documentId);
return Result.success(count);
}
}7.3 CommentController - 评论点赞端点
@PostMapping("/{commentId}/like")
@Operation(summary = "点赞评论", description = "点赞指定评论")
public Result<Boolean> likeComment(@PathVariable Long commentId) {
Boolean result = commentService.likeComment(commentId);
return Result.success(result);
}
@DeleteMapping("/{commentId}/like")
@Operation(summary = "取消点赞评论", description = "取消点赞评论")
public Result<Boolean> unlikeComment(@PathVariable Long commentId) {
Boolean result = commentService.unlikeComment(commentId);
return Result.success(result);
}7.4 RESTful API 设计总结
| 方法 | 路径 | 说明 | 所属 Controller |
|---|---|---|---|
| POST | /documents/{id}/like | 点赞文档 | DocumentController |
| DELETE | /documents/{id}/like | 取消点赞文档 | DocumentController |
| POST | /favorite/toggle/{id} | 切换收藏状态 | UserFavoriteController |
| POST | /favorite/add/{id} | 添加收藏 | UserFavoriteController |
| DELETE | /favorite/remove/{id} | 取消收藏 | UserFavoriteController |
| GET | /favorite/check/{id} | 检查收藏状态 | UserFavoriteController |
| GET | /favorite/list | 获取收藏列表 | UserFavoriteController |
| GET | /favorite/count/{id} | 获取收藏数量 | UserFavoriteController |
| POST | /comments/{id}/like | 点赞评论 | CommentController |
| DELETE | /comments/{id}/like | 取消点赞评论 | CommentController |
| GET | /documents/{id}/view | 浏览文档(+1计数) | DocumentController |
八、前端开发
8.1 定义 TypeScript 类型
// Document 类型(types/index.ts)
export interface Document {
id: string;
title: string;
content: string;
// ... 其他字段
viewCount?: number;
likeCount?: number;
commentCount?: number;
favoriteCount?: number;
isLiked?: boolean; // 当前用户是否已点赞
}
// Comment 类型(types/index.ts)
export interface Comment {
id: string | number;
documentId: string | number;
// ... 其他字段
likeCount: number;
replyCount: number;
isLiked: boolean; // 当前用户是否已点赞
}8.2 创建文档 API 服务层
在 src/services/document.service.ts 中添加:
export const documentService = {
// ... 其他方法
// 文档点赞
likeDocument: (id: string) =>
http.post(`/document/documents/${id}/like`),
// 取消文档点赞
unlikeDocument: (id: string) =>
http.delete(`/document/documents/${id}/like`),
// 浏览文档(+1计数)
viewDocument: (id: string) =>
http.get<Document>(`/document/documents/${id}/view`),
};8.3 创建收藏 API 服务层
创建 src/services/favorite.service.ts:
import { http } from './request';
export const favoriteService = {
// 切换收藏状态
toggleFavorite: (documentId: string) =>
http.post<boolean>(`/document/favorite/toggle/${documentId}`),
// 添加收藏
addFavorite: (documentId: string) =>
http.post<boolean>(`/document/favorite/add/${documentId}`),
// 取消收藏
removeFavorite: (documentId: string) =>
http.delete<boolean>(`/document/favorite/remove/${documentId}`),
// 检查收藏状态
checkFavorite: (documentId: string) =>
http.get<boolean>(`/document/favorite/check/${documentId}`),
// 获取收藏列表
getFavorites: () =>
http.get<any[]>('/document/favorite/list'),
// 获取文档收藏数量
getFavoriteCount: (documentId: string) =>
http.get<number>(`/document/favorite/count/${documentId}`),
};
export default favoriteService;8.4 创建评论 API 服务层
在 src/services/comment.service.ts 中添加:
export const commentService = {
// ... 其他方法
// 点赞评论
likeComment: (commentId: string | number) =>
http.post(`/document/comments/${commentId}/like`),
// 取消点赞评论
unlikeComment: (commentId: string | number) =>
http.delete(`/document/comments/${commentId}/like`),
};8.5 创建收藏状态管理 Store
创建 src/stores/favorite.store.ts:
import { create } from 'zustand';
import { favoriteService } from '@/services';
interface FavoriteState {
favorites: Map<string, boolean>; // documentId → isFavorited
isLoading: boolean;
favoriteDocuments: any[];
toggleFavorite: (documentId: string) => Promise<boolean>;
checkFavorite: (documentId: string) => Promise<void>;
loadFavorites: () => Promise<void>;
isFavorited: (documentId: string) => boolean;
}
export const useFavoriteStore = create<FavoriteState>((set, get) => ({
favorites: new Map<string, boolean>(),
isLoading: false,
favoriteDocuments: [],
toggleFavorite: async (documentId: string) => {
const isFavorited = await favoriteService.toggleFavorite(documentId);
set((state) => {
const newFavorites = new Map(state.favorites);
newFavorites.set(documentId, isFavorited);
return { favorites: newFavorites };
});
return isFavorited;
},
checkFavorite: async (documentId: string) => {
const isFavorited = await favoriteService.checkFavorite(documentId);
set((state) => {
const newFavorites = new Map(state.favorites);
newFavorites.set(documentId, isFavorited);
return { favorites: newFavorites };
});
},
loadFavorites: async () => {
set({ isLoading: true });
const data = await favoriteService.getFavorites();
const favoriteMap = new Map<string, boolean>();
data.forEach((item: any) => {
if (item.documentId) {
favoriteMap.set(String(item.documentId), true);
}
});
set({
favoriteDocuments: data,
favorites: favoriteMap,
isLoading: false,
});
},
isFavorited: (documentId: string) => {
return get().favorites.get(documentId) === true;
},
}));8.6 文档点赞 Store 逻辑
在 src/stores/document.store.ts 中的 likeDocument 方法:
likeDocument: async (id: string) => {
const currentDoc = get().currentDocument;
const isCurrentlyLiked = currentDoc?.id === id
? currentDoc.isLiked : false;
// 乐观更新:先切换本地状态
if (isCurrentlyLiked) {
await documentService.unlikeDocument(id);
} else {
await documentService.likeDocument(id);
}
// 同步更新 documents 列表和 currentDocument
set((state) => ({
documents: state.documents.map((doc) =>
doc.id === id
? {
...doc,
isLiked: !doc.isLiked,
likeCount: (doc.likeCount || 0)
+ (doc.isLiked ? -1 : 1),
}
: doc
),
currentDocument:
state.currentDocument?.id === id
? {
...state.currentDocument,
isLiked: !state.currentDocument.isLiked,
likeCount:
(state.currentDocument.likeCount || 0)
+ (state.currentDocument.isLiked ? -1 : 1),
}
: state.currentDocument,
}));
},8.7 文档详情页交互实现
在 DocumentDetailPage.tsx 中:
import { useDocumentStore, useFavoriteStore } from '@/stores';
import { commentService } from '@/services';
export const DocumentDetailPage: React.FC = () => {
const {
currentDocument, likeDocument
} = useDocumentStore();
const {
toggleFavorite, favorites
} = useFavoriteStore();
// 从 store 读取收藏状态
const isFavorited = useFavoriteStore((state) =>
state.favorites.get(currentDocument?.id || '') === true
);
// 从 store 读取点赞状态
const [liked, setLiked] = useState(false);
// 同步点赞状态
useEffect(() => {
if (currentDocument) {
setLiked(currentDocument.isLiked || false);
}
}, [currentDocument?.id, currentDocument?.isLiked]);
// 处理点赞
const handleLike = async () => {
if (!currentDoc) return;
try {
await likeDocument(currentDoc.id);
setLiked(!liked);
message.success(!liked ? '点赞成功' : '已取消点赞');
} catch (error) {
message.error('操作失败');
}
};
// 处理收藏
const handleFavorite = async () => {
if (!currentDocument?.id) return;
setFavoriteLoading(true);
try {
const newStatus = await toggleFavorite(currentDocument.id);
message.success(newStatus ? '已添加到收藏夹' : '已取消收藏');
} catch (error) {
message.error('操作失败,请重试');
} finally {
setFavoriteLoading(false);
}
};
// 处理评论点赞
const handleLikeComment = async (
commentId: string | number,
isLiked: boolean
) => {
try {
if (isLiked) {
await commentService.unlikeComment(commentId);
} else {
await commentService.likeComment(commentId);
}
// 刷新评论列表以获取最新 isLiked 状态
loadComments(commentPage.current);
} catch (error) {
message.error('操作失败');
}
};
return (
<>
{/* 点赞 + 收藏操作栏(放在文档内容和评论区之间) */}
{currentDoc.status === 1 && (
<div style={{
display: 'flex',
justifyContent: 'center',
gap: '16px',
padding: '20px 0',
}}>
{/* 收藏按钮 */}
<button onClick={handleFavorite}
disabled={favoriteLoading}
style={{ /* 药丸形按钮样式 */ }}>
{isFavorited ? <StarFilled /> : <StarOutlined />}
{isFavorited ? '已收藏' : '收藏文档'}
</button>
{/* 点赞按钮 */}
<button onClick={handleLike}
style={{ /* 药丸形按钮样式 */ }}>
{liked ? <LikeFilled /> : <LikeOutlined />}
{liked ? '已点赞' : '点赞'}
{Number(currentDoc.likeCount) > 0
? ` (${Number(currentDoc.likeCount)})` : ''}
</button>
</div>
)}
{/* 评论点赞按钮 */}
{comment.likeCount > 0 && comment.likeCount}
</>
);
};8.8 收藏管理页面
创建 src/pages/FavoritesPage.tsx,展示用户所有收藏的文档。
核心功能:
- 展示收藏列表(表格形式)
- 支持搜索筛选
- 支持单个/批量取消收藏
- 统计卡片(总数、本周新增、本月新增、未分类数)
- 双击跳转到文档详情
测试
按顺序启动下面这些微服务:
kb-gateway
kb-auth
kb-document
启动前端
cd knowledge-base-frontend
npm run dev
浏览器访问文档中心页面:
http://localhost:3002/documents

选择其中一个文档,打开文档详情页面:

在详情页最下面可以看到收藏、点赞按钮和评论列表。
发表评价:

点击发表评价按钮,可以看到评价成功了:

目前该文档已经收藏了,我们取消收藏:

由于该文档这个账号已经点赞过了,无法重复点赞,我就不给大家演示点赞功能了。
总结
本文详细介绍了文档评价和点赞功能的完整实现,涵盖文档点赞、文档收藏和评论点赞三大模块。
已完成功能
| 功能 | 实现方式 | 说明 |
|---|---|---|
| 文档点赞 | tb\_like + JdbcTemplate | 支持点赞/取消点赞,防重复 |
| 文档收藏 | kb\_user\_favorite + Service | 支持切换收藏/检查状态/列表查询 |
| 评论点赞 | tb\_like (target\_type=2) | 与文档点赞共用点赞表 |
| 浏览统计 | incrementViewCount SQL | 每次查看文档 +1 |
| 计数器管理 | GREATEREST(count-1, 0) | 安全递减,不会出现负数 |
| 前端交互 | Store + 乐观更新 | 先更新本地状态,后发API请求 |
| 收藏管理页 | FavoritesPage | 展示、搜索、批量取消收藏 |
通过本文的学习,你应该能够掌握:
- 统一点赞表的多态设计方法
- 物理删除 vs 逻辑删除的选择策略
- 计数器冗余与一致性保障
- 前端 Store 的乐观更新模式
- 批量查询优化和性能考虑
祝你开发顺利!