一、概述
文档版本管理是知识库系统的核心功能之一,它记录文档的每次修改历史,支持版本回溯、版本对比和版本恢复。本文将详细介绍如何在kb-document服务中实现完整的文档版本管理功能。
1.1 功能定位
版本管理作为文档控制的重要手段,提供以下核心功能:
| 功能模块 | 说明 | 使用场景 |
|---|---|---|
| 版本创建 | 自动记录文档修改历史 | 每次保存时自动创建版本 |
| 版本列表 | 查看文档的所有版本 | 版本历史浏览 |
| 版本详情 | 查看指定版本的完整内容 | 版本内容查看 |
| 版本恢复 | 恢复到指定历史版本 | 内容回滚 |
| 版本对比 | 比较两个版本的差异 | 变更查看 |
1.2 版本管理策略
自动版本创建策略:
- 每次保存文档时自动创建新版本
- 保留最近N个版本,旧版本可归档
版本编号规则:
- 版本号从1开始递增
- 每次修改自动递增
- 版本号全局唯一
1.3 数据模型
文档 (Document)
├── 版本1 (DocumentVersion) - 初始版本
├── 版本2 (DocumentVersion) - 第一次修改
├── 版本3 (DocumentVersion) - 第二次修改
└── ...二、数据库设计
2.1 文档版本表结构
CREATE TABLE `tb_document_version` (
`id` BIGINT NOT NULL COMMENT '版本ID',
`document_id` BIGINT NOT NULL COMMENT '文档ID',
`version` INT NOT NULL COMMENT '版本号',
`title` VARCHAR(200) NOT NULL COMMENT '文档标题',
`content` LONGTEXT NOT NULL COMMENT '文档内容',
`summary` TEXT DEFAULT NULL COMMENT '文档摘要',
`change_description` VARCHAR(500) DEFAULT NULL COMMENT '版本变更说明',
`change_size` BIGINT DEFAULT NULL COMMENT '变更大小(字节)',
`operator_id` BIGINT NOT NULL COMMENT '操作人ID',
`operator_name` VARCHAR(50) DEFAULT NULL COMMENT '操作人姓名',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_doc_version` (`document_id`, `version`),
KEY `idx_document_id` (`document_id`),
KEY `idx_operator_id` (`operator_id`),
KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='文档版本表';2.2 字段说明
| 字段 | 类型 | 说明 | 必填 | 默认值 |
|---|---|---|---|---|
| id | BIGINT | 版本ID | 是 | 自增 |
| document\_id | BIGINT | 文档ID | 是 | - |
| version | INT | 版本号 | 是 | - |
| title | VARCHAR(200) | 文档标题 | 是 | - |
| content | LONGTEXT | 文档内容 | 是 | - |
| summary | TEXT | 文档摘要 | 否 | - |
| change\_description | VARCHAR(500) | 版本变更说明 | 否 | - |
| change\_size | BIGINT | 变更大小(字节) | 否 | - |
| operator\_id | BIGINT | 操作人ID | 是 | - |
| operator\_name | VARCHAR(50) | 操作人姓名 | 否 | - |
| created\_at | DATETIME | 创建时间 | 是 | CURRENT\_TIMESTAMP |
2.3 索引设计
- 主键索引:
id- 主键唯一标识 - 唯一索引:
uk_doc_version- 确保每个文档的版本号唯一 - 普通索引:
idx_document_id- 加速按文档查询版本 - 普通索引:
idx_operator_id- 加速按操作人查询 - 普通索引:
idx_created_at- 加速按时间排序
三、实体类设计
3.1 创建DocumentVersion实体类
创建 kb-document/src/main/java/com/knowledge/base/document/entity/DocumentVersion.java:
package com.knowledge.base.document.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 文档版本实体
*
* @author 苏三
* @since 1.0.0
*/
@Data
@TableName("tb_document_version")
@Schema(description = "文档版本实体")
public class DocumentVersion {
/**
* 版本ID
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "版本ID")
private Long id;
/**
* 文档ID
*/
@Schema(description = "文档ID")
private Long documentId;
/**
* 版本号
*/
@Schema(description = "版本号")
private Integer version;
/**
* 文档标题
*/
@Schema(description = "文档标题")
private String title;
/**
* 文档内容
*/
@Schema(description = "文档内容")
private String content;
/**
* 文档摘要
*/
@Schema(description = "文档摘要")
private String summary;
/**
* 版本变更说明
*/
@Schema(description = "版本变更说明")
private String changeDescription;
/**
* 变更大小(字节)
*/
@Schema(description = "变更大小")
private Long changeSize;
/**
* 操作人ID
*/
@Schema(description = "操作人ID")
private Long operatorId;
/**
* 操作人姓名
*/
@Schema(description = "操作人姓名")
private String operatorName;
/**
* 创建时间
*/
@Schema(description = "创建时间")
private LocalDateTime createdAt;
}3.2 设计说明
- 版本号唯一性:使用
document_id和version的联合唯一索引 - 变更大小:记录与上一版本的内容差异大小
- 操作人信息:冗余操作人姓名,避免频繁关联查询
- 大字段存储:content使用LONGTEXT类型,支持大文档存储
四、DTO和VO设计
4.1 创建DocumentVersionRestoreDTO
创建 kb-document/src/main/java/com/knowledge/base/document/dto/DocumentVersionRestoreDTO.java:
package com.knowledge.base.document.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 文档版本恢复DTO
*
* @author 苏三
* @since 1.0.0
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "文档版本恢复参数")
public class DocumentVersionRestoreDTO {
/**
* 版本ID
*/
@Schema(description = "版本ID")
@NotNull(message = "版本ID不能为空")
private Long versionId;
/**
* 恢复原因
*/
@Schema(description = "恢复原因")
private String reason;
}4.2 创建DocumentVersionVO
创建 kb-document/src/main/java/com/knowledge/base/document/vo/DocumentVersionVO.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;
/**
* 文档版本VO
*
* @author 苏三
* @since 1.0.0
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "文档版本信息")
public class DocumentVersionVO {
/**
* 版本ID
*/
@Schema(description = "版本ID")
private Long id;
/**
* 文档ID
*/
@Schema(description = "文档ID")
private Long documentId;
/**
* 版本号
*/
@Schema(description = "版本号")
private Integer version;
/**
* 文档标题
*/
@Schema(description = "文档标题")
private String title;
/**
* 版本变更说明
*/
@Schema(description = "版本变更说明")
private String changeDescription;
/**
* 变更大小(字节)
*/
@Schema(description = "变更大小")
private Long changeSize;
/**
* 操作人ID
*/
@Schema(description = "操作人ID")
private Long operatorId;
/**
* 操作人姓名
*/
@Schema(description = "操作人姓名")
private String operatorName;
/**
* 创建时间
*/
@Schema(description = "创建时间")
private LocalDateTime createdAt;
}4.3 设计说明
DTO vs VO的区别:
| 类型 | 用途 | 特点 |
|---|---|---|
| RestoreDTO | 接收恢复请求 | 简洁,只包含必要参数 |
| VO | 返回版本信息 | 包含所有展示字段 |
数据安全考虑:
- VO不返回完整的content内容,避免响应过大
- 查看版本详情时才返回完整内容
五、数据访问层
5.1 创建Mapper接口
创建 kb-document/src/main/java/com/knowledge/base/document/mapper/DocumentVersionMapper.java:
package com.knowledge.base.document.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.knowledge.base.document.entity.DocumentVersion;
import org.apache.ibatis.annotations.Mapper;
/**
* 文档版本Mapper接口
*
* @author 苏三
* @since 1.0.0
*/
@Mapper
public interface DocumentVersionMapper extends BaseMapper<DocumentVersion> {
}5.2 创建Mapper XML
创建 kb-document/src/main/resources/mapper/DocumentVersionMapper.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.DocumentVersionMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.knowledge.base.document.entity.DocumentVersion">
<id column="id" property="id" />
<result column="document_id" property="documentId" />
<result column="version" property="version" />
<result column="title" property="title" />
<result column="content" property="content" />
<result column="summary" property="summary" />
<result column="change_description" property="changeDescription" />
<result column="change_size" property="changeSize" />
<result column="operator_id" property="operatorId" />
<result column="operator_name" property="operatorName" />
<result column="created_at" property="createdAt" />
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
id, document_id, version, title, content, summary, change_description, change_size,
operator_id, operator_name, created_at
</sql>
<!-- 根据文档ID查询版本列表 -->
<select id="selectByDocumentId" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM tb_document_version
WHERE document_id = #{documentId}
ORDER BY version DESC
</select>
<!-- 根据文档ID和版本号查询版本 -->
<select id="selectByDocumentIdAndVersion" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM tb_document_version
WHERE document_id = #{documentId}
AND version = #{version}
LIMIT 1
</select>
<!-- 查询文档的最新版本 -->
<select id="selectLatestByDocumentId" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM tb_document_version
WHERE document_id = #{documentId}
ORDER BY version DESC
LIMIT 1
</select>
<!-- 查询文档的第一个版本 -->
<select id="selectFirstByDocumentId" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM tb_document_version
WHERE document_id = #{documentId}
ORDER BY version ASC
LIMIT 1
</select>
<!-- 获取文档的下一个版本号 -->
<select id="getNextVersionNumber" resultType="java.lang.Integer">
SELECT COALESCE(MAX(version), 0) + 1
FROM tb_document_version
WHERE document_id = #{documentId}
</select>
<!-- 统计文档的版本数量 -->
<select id="countByDocumentId" resultType="java.lang.Long">
SELECT COUNT(*)
FROM tb_document_version
WHERE document_id = #{documentId}
</select>
<!-- 根据操作人ID查询版本列表 -->
<select id="selectByOperatorId" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM tb_document_version
WHERE operator_id = #{operatorId}
ORDER BY created_at DESC
</select>
<!-- 比较两个版本 -->
<select id="compareVersions" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM tb_document_version
WHERE document_id = #{documentId}
AND version IN (#{version1}, #{version2})
ORDER BY version ASC
</select>
</mapper>5.3 Mapper方法说明
| 方法 | 说明 | 使用场景 |
|---|---|---|
| selectByDocumentId | 查询文档所有版本 | 版本列表展示 |
| selectByDocumentIdAndVersion | 查询指定版本 | 版本详情查看 |
| selectLatestByDocumentId | 查询最新版本 | 获取最新内容 |
| selectFirstByDocumentId | 查询首个版本 | 查看初始版本 |
| getNextVersionNumber | 获取下一版本号 | 创建新版本时 |
| countByDocumentId | 统计版本数量 | 版本数量统计 |
| selectByOperatorId | 查询操作人的版本 | 操作历史查询 |
| compareVersions | 比较两个版本 | 版本对比功能 |
六、业务逻辑层
6.1 创建Service接口
创建 kb-document/src/main/java/com/knowledge/base/document/service/DocumentVersionService.java:
package com.knowledge.base.document.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.knowledge.base.document.dto.DocumentVersionRestoreDTO;
import com.knowledge.base.document.vo.DocumentVersionVO;
import java.util.List;
/**
* 文档版本管理服务接口
*
* @author 苏三
* @since 1.0.0
*/
public interface DocumentVersionService {
/**
* 创建文档版本
*
* @param documentId 文档ID
* @param changeDescription 变更说明
* @param userId 用户ID
* @return 是否成功
*/
boolean createVersion(Long documentId, String changeDescription, Long userId);
/**
* 获取文档版本列表
*
* @param documentId 文档ID
* @param current 当前页
* @param size 每页大小
* @return 版本列表
*/
IPage<DocumentVersionVO> getVersionList(Long documentId, Long current, Long size);
/**
* 获取版本详情
*
* @param versionId 版本ID
* @return 版本详情
*/
DocumentVersionVO getVersionDetail(Long versionId);
/**
* 恢复版本
*
* @param documentId 文档ID
* @param restoreDTO 恢复参数
* @param userId 用户ID
* @return 是否成功
*/
boolean restoreVersion(Long documentId, DocumentVersionRestoreDTO restoreDTO, Long userId);
/**
* 对比版本差异
*
* @param versionId1 版本ID1
* @param versionId2 版本ID2
* @return 差异内容
*/
String compareVersions(Long versionId1, Long versionId2);
/**
* 删除版本
*
* @param versionId 版本ID
* @param userId 用户ID
* @return 是否成功
*/
boolean deleteVersion(Long versionId, Long userId);
}6.2 创建Service实现类
创建 kb-document/src/main/java/com/knowledge/base/document/service/impl/DocumentVersionServiceImpl.java:
package com.knowledge.base.document.service.impl;
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.knowledge.base.common.exception.BusinessException;
import com.knowledge.base.common.utils.SnowflakeIdGenerator;
import com.knowledge.base.document.dto.DocumentVersionRestoreDTO;
import com.knowledge.base.document.entity.Document;
import com.knowledge.base.document.entity.DocumentVersion;
import com.knowledge.base.document.mapper.DocumentMapper;
import com.knowledge.base.document.mapper.DocumentVersionMapper;
import com.knowledge.base.document.service.DocumentVersionService;
import com.knowledge.base.document.vo.DocumentVersionVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
/**
* 文档版本Service实现类
*
* <p>按照阿里巴巴Java开发规范设计,实现文档版本相关业务逻辑</p>
*
* @author 苏三
* @since 1.0.0
*/
@Slf4j
@Service
public class DocumentVersionServiceImpl implements DocumentVersionService {
@Resource
private DocumentVersionMapper documentVersionMapper;
@Resource
private DocumentMapper documentMapper;
@Override
@Transactional(rollbackFor = Exception.class)
public boolean createVersion(Long documentId, String changeDescription, Long userId) {
log.info("创建文档版本:documentId={}, userId={}", documentId, userId);
if (documentId == null) {
throw new BusinessException("文档ID不能为空");
}
// 获取文档信息
Document document = documentMapper.selectById(documentId);
if (document == null) {
throw new BusinessException("文档不存在");
}
// 获取当前最大版本号
Long currentVersionCount = documentVersionMapper.selectCount(
new LambdaQueryWrapper<DocumentVersion>()
.eq(DocumentVersion::getDocumentId, documentId)
);
Integer currentVersion = currentVersionCount.intValue();
// 获取上一个版本以计算变更大小
Long changeSize = 0L;
DocumentVersion lastVersion = documentVersionMapper.selectOne(
new LambdaQueryWrapper<DocumentVersion>()
.eq(DocumentVersion::getDocumentId, documentId)
.orderByDesc(DocumentVersion::getVersion)
.last("LIMIT 1")
);
if (lastVersion != null && lastVersion.getContent() != null) {
int oldSize = lastVersion.getContent().length();
int newSize = document.getContent() != null ? document.getContent().length() : 0;
changeSize = (long) newSize - oldSize;
}
// TODO: 获取操作人信息
String operatorName = "系统用户";
// 创建版本记录
DocumentVersion version = new DocumentVersion();
version.setId(SnowflakeIdGenerator.getInstance().nextId());
version.setDocumentId(documentId);
version.setVersion(currentVersion + 1);
version.setTitle(document.getTitle());
version.setContent(document.getContent());
version.setSummary(document.getSummary());
version.setChangeDescription(changeDescription);
version.setChangeSize(changeSize);
version.setOperatorId(userId);
version.setOperatorName(operatorName);
version.setCreatedAt(LocalDateTime.now());
int count = documentVersionMapper.insert(version);
return count > 0;
}
@Override
public IPage<DocumentVersionVO> getVersionList(Long documentId, Long current, Long size) {
if (documentId == null) {
throw new BusinessException("文档ID不能为空");
}
// 检查文档是否存在
Document document = documentMapper.selectById(documentId);
if (document == null) {
throw new BusinessException("文档不存在");
}
// 分页查询版本列表
Page<DocumentVersion> page = new Page<>(current, size);
IPage<DocumentVersion> versionPage = documentVersionMapper.selectPage(
page,
new LambdaQueryWrapper<DocumentVersion>()
.eq(DocumentVersion::getDocumentId, documentId)
.orderByDesc(DocumentVersion::getVersion)
);
// 转换为VO
return versionPage.convert(this::convertToVO);
}
@Override
public DocumentVersionVO getVersionDetail(Long versionId) {
if (versionId == null) {
throw new BusinessException("版本ID不能为空");
}
DocumentVersion version = documentVersionMapper.selectById(versionId);
if (version == null) {
throw new BusinessException("版本不存在");
}
return convertToVO(version);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean restoreVersion(Long documentId, DocumentVersionRestoreDTO restoreDTO, Long userId) {
log.info("恢复文档版本:documentId={}, versionId={}, userId={}", documentId, restoreDTO.getVersionId(), userId);
if (documentId == null) {
throw new BusinessException("文档ID不能为空");
}
// 检查文档是否存在
Document document = documentMapper.selectById(documentId);
if (document == null) {
throw new BusinessException("文档不存在");
}
// 检查版本是否存在
DocumentVersion version = documentVersionMapper.selectById(restoreDTO.getVersionId());
if (version == null) {
throw new BusinessException("版本不存在");
}
// 检查版本是否属于该文档
if (!version.getDocumentId().equals(documentId)) {
throw new BusinessException("版本不属于该文档");
}
// 创建当前版本的备份(恢复前)
createVersion(documentId, "恢复前自动备份", userId);
// 恢复文档内容
document.setTitle(version.getTitle());
document.setContent(version.getContent());
document.setSummary(version.getSummary());
documentMapper.updateById(document);
return true;
}
@Override
public String compareVersions(Long versionId1, Long versionId2) {
if (versionId1 == null || versionId2 == null) {
throw new BusinessException("版本ID不能为空");
}
if (versionId1.equals(versionId2)) {
throw new BusinessException("不能比较相同的版本");
}
DocumentVersion version1 = documentVersionMapper.selectById(versionId1);
DocumentVersion version2 = documentVersionMapper.selectById(versionId2);
if (version1 == null || version2 == null) {
throw new BusinessException("版本不存在");
}
// 构建差异对比结果
StringBuilder diff = new StringBuilder();
diff.append("=== 版本对比 ===\n");
diff.append(String.format("版本 %d vs 版本 %d\n", version1.getVersion(), version2.getVersion()));
diff.append("\n");
// 标题差异
if (!version1.getTitle().equals(version2.getTitle())) {
diff.append("【标题差异】\n");
diff.append(String.format("- 版本%d: %s\n", version1.getVersion(), version1.getTitle()));
diff.append(String.format("+ 版本%d: %s\n", version2.getVersion(), version2.getTitle()));
diff.append("\n");
}
// 内容差异(简单实现,实际可以使用diff库)
String content1 = version1.getContent() != null ? version1.getContent() : "";
String content2 = version2.getContent() != null ? version2.getContent() : "";
if (!content1.equals(content2)) {
diff.append("【内容差异】\n");
diff.append(String.format("版本%d 内容长度: %d 字符\n", version1.getVersion(), content1.length()));
diff.append(String.format("版本%d 内容长度: %d 字符\n", version2.getVersion(), content2.length()));
diff.append(String.format("差异大小: %d 字符\n", content2.length() - content1.length()));
}
return diff.toString();
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean deleteVersion(Long versionId, Long userId) {
log.info("删除文档版本:versionId={}, userId={}", versionId, userId);
if (versionId == null) {
throw new BusinessException("版本ID不能为空");
}
// 检查版本是否存在
DocumentVersion version = documentVersionMapper.selectById(versionId);
if (version == null) {
throw new BusinessException("版本不存在");
}
// 检查是否是最新版本
Long count = documentVersionMapper.selectCount(
new LambdaQueryWrapper<DocumentVersion>()
.eq(DocumentVersion::getDocumentId, version.getDocumentId())
.gt(DocumentVersion::getVersion, version.getVersion())
);
if (count > 0) {
throw new BusinessException("不能删除中间版本,只能删除最新版本");
}
// 删除版本
int deleteCount = documentVersionMapper.deleteById(versionId);
return deleteCount > 0;
}
/**
* 转换为VO
*
* @param version 版本实体
* @return 版本VO
*/
private DocumentVersionVO convertToVO(DocumentVersion version) {
return DocumentVersionVO.builder()
.id(version.getId())
.documentId(version.getDocumentId())
.version(version.getVersion())
.title(version.getTitle())
.changeDescription(version.getChangeDescription())
.changeSize(version.getChangeSize())
.operatorId(version.getOperatorId())
.operatorName(version.getOperatorName())
.createdAt(version.getCreatedAt())
.build();
}
}6.3 核心方法说明
6.3.1 版本创建逻辑
版本创建的关键步骤:
- 获取当前文档的最大版本号
- 计算与上一版本的变更大小
- 创建新版本记录
设计优势:
- 自动递增版本号
- 记录变更大小便于分析
- 保存完整文档快照
6.3.2 版本恢复逻辑
版本恢复采用"恢复前备份"策略:
// 创建当前版本的备份(恢复前)
createVersion(documentId, "恢复前自动备份", userId);
// 恢复文档内容
document.setTitle(version.getTitle());
document.setContent(version.getContent());
document.setSummary(version.getSummary());设计优势:
- 防止误操作导致数据丢失
- 保留完整的修改历史
- 支持回滚到恢复前的状态
七、控制器层
7.1 创建DocumentVersionController
创建 kb-document/src/main/java/com/knowledge/base/document/controller/DocumentVersionController.java:
package com.knowledge.base.document.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.knowledge.base.common.result.Result;
import com.knowledge.base.document.dto.DocumentVersionRestoreDTO;
import com.knowledge.base.document.service.DocumentVersionService;
import com.knowledge.base.document.vo.DocumentVersionVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
/**
* 文档版本管理Controller
*
* <p>按照阿里巴巴Java开发规范设计,提供文档版本管理相关接口</p>
*
* @author 苏三
* @since 1.0.0
*/
@Slf4j
@RestController
@RequestMapping("/documents/{documentId}/versions")
@Tag(name = "文档版本管理", description = "文档版本管理接口")
public class DocumentVersionController {
@Resource
private DocumentVersionService documentVersionService;
/**
* 获取文档版本列表
*
* @param documentId 文档ID
* @param current 当前页
* @param size 每页大小
* @return 版本分页信息
*/
@GetMapping
@Operation(summary = "获取文档版本列表", description = "分页查询文档版本列表")
public Result<IPage<DocumentVersionVO>> getVersions(
@Parameter(description = "文档ID", required = true)
@PathVariable Long documentId,
@Parameter(description = "当前页") @RequestParam(defaultValue = "1") Long current,
@Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Long size) {
log.info("获取文档版本列表请求:documentId={}, current={}, size={}", documentId, current, size);
IPage<DocumentVersionVO> page = documentVersionService.getVersionList(documentId, current, size);
return Result.success(page);
}
/**
* 获取文档版本详情
*
* @param documentId 文档ID
* @param versionId 版本ID
* @return 版本详情
*/
@GetMapping("/{versionId}")
@Operation(summary = "获取文档版本详情", description = "根据版本ID获取版本详情")
public Result<DocumentVersionVO> getVersionDetail(
@Parameter(description = "文档ID", required = true)
@PathVariable Long documentId,
@Parameter(description = "版本ID", required = true)
@PathVariable Long versionId) {
log.info("获取文档版本详情请求:documentId={}, versionId={}", documentId, versionId);
DocumentVersionVO versionVO = documentVersionService.getVersionDetail(versionId);
return Result.success(versionVO);
}
/**
* 恢复文档版本
*
* @param documentId 文档ID
* @param dto 恢复版本DTO
* @return 是否成功
*/
@PostMapping("/restore")
@Operation(summary = "恢复文档版本", description = "将文档恢复到指定版本")
public Result<Boolean> restoreVersion(
@Parameter(description = "文档ID", required = true)
@PathVariable Long documentId,
@Valid @RequestBody DocumentVersionRestoreDTO dto) {
log.info("恢复文档版本请求:documentId={}, versionId={}", documentId, dto.getVersionId());
// TODO: 从上下文获取当前用户ID
Long userId = 1L;
Boolean success = documentVersionService.restoreVersion(documentId, dto, userId);
return Result.success("恢复版本成功", success);
}
/**
* 对比两个版本
*
* @param documentId 文档ID
* @param versionId1 版本1 ID
* @param versionId2 版本2 ID
* @return 对比结果
*/
@GetMapping("/compare")
@Operation(summary = "对比文档版本", description = "对比两个文档版本的差异")
public Result<String> compareVersions(
@Parameter(description = "文档ID", required = true)
@PathVariable Long documentId,
@Parameter(description = "版本1 ID", required = true)
@RequestParam Long versionId1,
@Parameter(description = "版本2 ID", required = true)
@RequestParam Long versionId2) {
log.info("对比文档版本请求:documentId={}, versionId1={}, versionId2={}",
documentId, versionId1, versionId2);
String diff = documentVersionService.compareVersions(versionId1, versionId2);
return Result.success(diff);
}
}7.2 RESTful API设计
| 方法 | 路径 | 说明 | 参数 |
|---|---|---|---|
| GET | /documents/{id}/versions | 获取版本列表 | documentId, current, size |
| GET | /documents/{id}/versions/{versionId} | 获取版本详情 | documentId, versionId |
| POST | /documents/{id}/versions/restore | 恢复版本 | documentId, RestoreDTO |
| GET | /documents/{id}/versions/compare | 对比版本 | documentId, versionId1, versionId2 |
八、集成文档服务
8.1 在DocumentService中集成版本创建
在更新文档时自动创建版本,修改 DocumentServiceImpl 的 updateDocument 方法:
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean updateDocument(DocumentDTO documentDTO) {
log.info("更新文档:documentId={}", documentDTO.getId());
if (documentDTO.getId() == null) {
throw new BusinessException("文档ID不能为空");
}
// 获取更新前的文档(用于创建版本)
Document oldDocument = documentMapper.selectById(documentDTO.getId());
if (oldDocument == null) {
throw new BusinessException("文档不存在");
}
// 更新文档
Document document = new Document();
BeanUtil.copyProperties(documentDTO, document);
// 如果状态从草稿变为发布,设置发布时间
if (Objects.equals(oldDocument.getStatus(), 0)
&& Objects.equals(documentDTO.getStatus(), 1)) {
document.setPublishTime(LocalDateTime.now());
}
int count = documentMapper.updateById(document);
// 自动创建版本
if (count > 0) {
// TODO: 从上下文获取当前用户ID
Long userId = 1L;
String changeDescription = buildChangeDescription(oldDocument, document);
documentVersionService.createVersion(documentDTO.getId(), changeDescription, userId);
}
return count > 0;
}
/**
* 构建变更说明
*/
private String buildChangeDescription(Document oldDocument, Document newDocument) {
List<String> changes = new ArrayList<>();
if (!Objects.equals(oldDocument.getTitle(), newDocument.getTitle())) {
changes.add("标题变更");
}
if (!Objects.equals(oldDocument.getContent(), newDocument.getContent())) {
changes.add("内容更新");
}
if (!Objects.equals(oldDocument.getCategoryId(), newDocument.getCategoryId())) {
changes.add("分类调整");
}
return changes.isEmpty() ? "文档更新" : String.join("、", changes);
}九、测试验证
9.1 测试版本功能
创建文档并生成版本
# 1. 创建文档(自动生成版本1)
curl -X POST http://localhost:8082/api/document/documents \
-H "Content-Type: application/json" \
-d '{
"title": "Spring Boot 3.x 入门指南",
"summary": "本文介绍Spring Boot 3.x的基础知识",
"content": "Spring Boot 3.x 是基于Spring Framework 6.x构建的...",
"documentType": 1,
"status": 1
}'
# 2. 更新文档(自动生成版本2)
curl -X PUT http://localhost:8082/api/document/documents \
-H "Content-Type: application/json" \
-d '{
"id": 1,
"title": "Spring Boot 3.x 入门指南(更新版)",
"content": "Spring Boot 3.x 是基于Spring Framework 6.x构建的...(更新内容)"
}'获取版本列表
curl "http://localhost:8082/api/document/documents/1/versions?current=1&size=10"返回示例:
{
"code": 200,
"message": "操作成功",
"data": {
"records": [
{
"id": 1000000000000000001,
"documentId": 1,
"version": 2,
"title": "Spring Boot 3.x 入门指南(更新版)",
"changeDescription": "内容更新",
"changeSize": 256,
"operatorId": 1,
"operatorName": "系统用户",
"createdAt": "2026-05-13T14:30:00"
},
{
"id": 1000000000000000000,
"documentId": 1,
"version": 1,
"title": "Spring Boot 3.x 入门指南",
"changeDescription": null,
"changeSize": 0,
"operatorId": 1,
"operatorName": "系统用户",
"createdAt": "2026-05-13T14:00:00"
}
],
"total": 2,
"current": 1,
"size": 10
}
}恢复版本
curl -X POST http://localhost:8082/api/document/documents/1/versions/restore \
-H "Content-Type: application/json" \
-d '{
"versionId": 1000000000000000000,
"reason": "需要回滚到初始版本"
}'对比版本
curl "http://localhost:8082/api/document/documents/1/versions/compare?versionId1=1000000000000000000&versionId2=1000000000000000001"返回示例:
=== 版本对比 ===
版本 1 vs 版本 2
【标题差异】
- 版本1: Spring Boot 3.x 入门指南
+ 版本2: Spring Boot 3.x 入门指南(更新版)
【内容差异】
版本1 内容长度: 5000 字符
版本2 内容长度: 5256 字符
差异大小: 256 字符总结
本文详细介绍了文档版本管理功能的完整实现,涵盖了以下核心内容:
已完成功能
| 功能 | 实现方式 | 说明 |
|---|---|---|
| 版本创建 | 自动触发 | 文档更新时自动创建 |
| 版本列表 | 分页查询 | 按版本号倒序排列 |
| 版本详情 | 完整查询 | 包含标题、内容、操作人等 |
| 版本恢复 | 恢复+备份 | 自动备份当前版本 |
| 版本对比 | 文本对比 | 显示标题和内容差异 |
| 版本删除 | 最新版本 | 只能删除最新版本 |