一、概述

文档服务(kb-document)是企业知识库系统的核心模块,负责文档的创建、编辑、发布、查询、评论、审核等全生命周期管理。

本文将详细介绍如何从零开始搭建文档服务模块。

1.1 服务定位

文档服务作为系统的核心业务模块,提供以下功能:

功能模块说明使用场景
文档管理文档CRUD、发布、归档知识库内容管理
分类管理树形分类结构文档组织归类
标签管理标签CRUD、关联文档标记和检索
评论管理评论、回复、点赞用户互动交流
版本管理文档版本历史版本回溯对比
审核管理文档审核流程内容质量控制
文件上传文档文件上传Office、PDF等文件

1.2 技术架构

kb-document
├── 数据持久层:MyBatis Plus + MySQL
├── 缓存层:Redis(文档浏览量、热点数据)
├── 搜索层:Elasticsearch(全文检索)
├── 文件处理:Apache POI、PDFBox
├── API文档:Knife4j
└── 基础设施:Spring Boot 3.2

1.3 核心实体关系

Document (文档)
    ├── Category (分类) - 多对一
    ├── Tag (标签) - 多对多
    ├── Comment (评论) - 一对多
    ├── DocumentVersion (版本) - 一对多
    └── DocumentReview (审核) - 一对多

二、环境准备

2.1 创建数据库

mysql -u root -p -e "CREATE DATABASE kb_document DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"

2.2 安装Elasticsearch(可选)

文档服务支持全文检索功能,需要安装Elasticsearch:

# 使用Docker安装Elasticsearch
docker run -d \
  --name elasticsearch \
  -p 9200:9200 \
  -p 9300:9300 \
  -e "discovery.type=single-node" \
  -e "ES_JAVA_OPTS=-Xms512m -Xmx512m" \
  elasticsearch:8.11.0

如果不想自己在本地安装,可以直接连接星球中我在云服务器中部署好的。

三、创建模块骨架

3.1 创建Maven模块

mkdir -p kb-document/src/main/java/com/knowledge/base/document
mkdir -p kb-document/src/main/resources/mapper

3.2 配置pom.xml

创建 kb-document/pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.knowledge.base</groupId>
        <artifactId>knowledge-base-backend</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
    <artifactId>kb-document</artifactId>
    <packaging>jar</packaging>
    <name>Knowledge Base Document Service</name>
    <description>文档服务(核心)</description>
    <dependencies>
        <!-- 公共模块 -->
        <dependency>
            <groupId>com.knowledge.base</groupId>
            <artifactId>kb-common</artifactId>
        </dependency>
        <!-- Spring Boot Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Spring Boot Validation -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <!-- MySQL驱动 -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- Druid数据源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-3-starter</artifactId>
        </dependency>
        <!-- MyBatis Plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
        </dependency>
        <!-- Redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- Elasticsearch -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <!-- Hutool -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
        </dependency>
        <!-- Apache POI(文档处理) -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.5</version>
        </dependency>
        <!-- PDFBox(PDF处理) -->
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.29</version>
        </dependency>
        <!-- Lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- Knife4j -->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
        </dependency>
        <!-- Test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

四、数据库设计

4.1 文档表 (kb\_document)

CREATE TABLE `kb_document` (
  `id` BIGINT NOT NULL COMMENT '文档ID',
  `title` VARCHAR(200) NOT NULL COMMENT '文档标题',
  `content` LONGTEXT NOT NULL COMMENT '文档内容',
  `summary` TEXT DEFAULT NULL COMMENT '文档摘要',
  `category_id` BIGINT DEFAULT NULL COMMENT '分类ID',
  `author_id` BIGINT NOT NULL COMMENT '作者ID',
  `author_name` VARCHAR(50) DEFAULT NULL COMMENT '作者姓名(冗余字段)',
  `cover_image` VARCHAR(500) DEFAULT NULL COMMENT '封面图片',
  `status` VARCHAR(20) NOT NULL DEFAULT 'draft' COMMENT '状态',
  `is_public` TINYINT NOT NULL DEFAULT 1 COMMENT '是否公开',
  `is_top` TINYINT NOT NULL DEFAULT 0 COMMENT '是否置顶',
  `allow_comment` TINYINT NOT NULL DEFAULT 1 COMMENT '允许评论',
  `view_count` INT NOT NULL DEFAULT 0 COMMENT '浏览次数',
  `like_count` INT NOT NULL DEFAULT 0 COMMENT '点赞次数',
  `comment_count` INT NOT NULL DEFAULT 0 COMMENT '评论次数',
  `collect_count` INT NOT NULL DEFAULT 0 COMMENT '收藏次数',
  `version` INT NOT NULL DEFAULT 1 COMMENT '版本号',
  `word_count` INT DEFAULT NULL COMMENT '字数',
  `publish_time` DATETIME DEFAULT NULL 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`),
  KEY `idx_title` (`title`(100)),
  KEY `idx_category_id` (`category_id`),
  KEY `idx_author_id` (`author_id`),
  KEY `idx_status` (`status`),
  KEY `idx_publish_time` (`publish_time`),
  FULLTEXT KEY `ft_content` (`title`, `content`, `summary`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='文档表';

4.2 分类表 (kb\_category)

CREATE TABLE `kb_category` (
  `id` BIGINT NOT NULL COMMENT '分类ID',
  `category_name` VARCHAR(50) NOT NULL COMMENT '分类名称',
  `parent_id` BIGINT NOT NULL DEFAULT 0 COMMENT '父分类ID',
  `category_icon` VARCHAR(50) DEFAULT '📁' COMMENT '分类图标',
  `description` VARCHAR(500) DEFAULT NULL COMMENT '分类描述',
  `sort` INT NOT NULL DEFAULT 0 COMMENT '排序号',
  `document_count` INT NOT NULL DEFAULT 0 COMMENT '文档数量',
  `status` TINYINT NOT NULL DEFAULT 1 COMMENT '状态',
  `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `create_by` BIGINT DEFAULT NULL COMMENT '创建人',
  `update_by` BIGINT DEFAULT NULL COMMENT '更新人',
  `deleted` TINYINT NOT NULL DEFAULT 0 COMMENT '删除标识',
  PRIMARY KEY (`id`),
  KEY `idx_parent_id` (`parent_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='文档分类表';

4.3 标签表 (tb\_tag)

CREATE TABLE `tb_tag` (
  `id` BIGINT NOT NULL COMMENT '标签ID',
  `tag_name` VARCHAR(50) NOT NULL COMMENT '标签名称',
  `tag_code` VARCHAR(50) DEFAULT NULL COMMENT '标签编码',
  `tag_type` VARCHAR(20) DEFAULT 'USER' COMMENT '标签类型:SYSTEM-系统标签,USER-用户标签',
  `color` VARCHAR(20) DEFAULT NULL COMMENT '标签颜色',
  `icon` VARCHAR(50) DEFAULT NULL COMMENT '标签图标',
  `doc_count` INT NOT NULL DEFAULT 0 COMMENT '文档数量',
  `status` TINYINT NOT NULL DEFAULT 1 COMMENT '状态:0-禁用,1-正常',
  `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_tag_code` (`tag_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='标签表';

4.4 评论表 (tb\_comment)

CREATE TABLE `tb_comment` (
  `id` BIGINT NOT NULL COMMENT '评论ID',
  `document_id` BIGINT NOT NULL COMMENT '文档ID',
  `content` TEXT NOT NULL COMMENT '评论内容',
  `user_id` BIGINT NOT NULL COMMENT '评论用户ID',
  `user_name` VARCHAR(50) DEFAULT NULL COMMENT '用户姓名(冗余字段)',
  `user_avatar` VARCHAR(500) DEFAULT NULL COMMENT '用户头像(冗余字段)',
  `parent_id` BIGINT NOT NULL DEFAULT 0 COMMENT '父评论ID',
  `root_id` BIGINT NOT NULL DEFAULT 0 COMMENT '根评论ID',
  `reply_to_user_id` BIGINT DEFAULT NULL COMMENT '回复的用户ID',
  `reply_to_user_name` VARCHAR(50) DEFAULT NULL COMMENT '回复给谁(冗余字段)',
  `like_count` INT NOT NULL DEFAULT 0 COMMENT '点赞数',
  `reply_count` INT NOT NULL DEFAULT 0 COMMENT '回复数',
  `status` TINYINT NOT NULL DEFAULT 1 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`),
  KEY `idx_document_id` (`document_id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_parent_id` (`parent_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='评论表';

4.5 文档版本表 (tb\_document\_version)

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`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='文档版本表';

4.6 文档审核表 (tb\_document\_review)

CREATE TABLE `tb_document_review` (
  `id` BIGINT NOT NULL COMMENT '审核ID',
  `document_id` BIGINT NOT NULL COMMENT '文档ID',
  `reviewer_id` BIGINT NOT NULL COMMENT '审核人ID',
  `reviewer_name` VARCHAR(50) DEFAULT NULL COMMENT '审核人姓名',
  `review_result` INT NOT NULL COMMENT '审核结果:1-通过,2-驳回',
  `review_comment` TEXT DEFAULT NULL COMMENT '审核意见',
  `before_status` INT DEFAULT NULL COMMENT '审核前状态',
  `reviewed_at` DATETIME DEFAULT NULL COMMENT '审核时间',
  `review_round` INT NOT NULL DEFAULT 1 COMMENT '审核轮次',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`),
  KEY `idx_document_id` (`document_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='文档审核表';

4.7 文档标签关联表 (kb\_document\_tag)

CREATE TABLE `kb_document_tag` (
  `id` BIGINT NOT NULL COMMENT '主键ID',
  `document_id` BIGINT NOT NULL COMMENT '文档ID',
  `tag_id` BIGINT NOT NULL COMMENT '标签ID',
  `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_document_tag` (`document_id`, `tag_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='文档标签关联表';

五、应用配置

5.1 创建启动类

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

package com.knowledge.base.document;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

/**
 * 文档服务启动类
 *
 * @author 苏三
 * @since 1.0.0
 */
@SpringBootApplication
@ComponentScan(basePackages = {"com.knowledge.base.document", "com.knowledge.base.common"})
public class DocumentApplication {

    public static void main(String[] args) {
        SpringApplication.run(DocumentApplication.class, args);
        System.out.println("========================================");
        System.out.println("文档服务启动成功!");
        System.out.println("Swagger文档地址: http://localhost:8082/api/document/doc.html");
        System.out.println("========================================");
    }
}

5.2 配置application.yml

创建 kb-document/src/main/resources/application.yml:

server:
  port: 8082
  servlet:
    context-path: /api/document

spring:
  application:
    name: kb-document

  # 数据源配置
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/kb_document?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
    username: root
    password: 123456
    druid:
      initial-size: 20
      min-idle: 10
      max-active: 100
      max-wait: 60000
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      validation-query: SELECT 1
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      filters: stat,wall
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      web-stat-filter:
        enabled: true
        url-pattern: /*
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        reset-enable: false
        login-username: admin
        login-password: admin

  # Redis配置(可选)
  redis:
    host: localhost
    port: 6379
    password:
    database: 1
    timeout: 10000ms
    lettuce:
      pool:
        max-active: 8
        max-wait: -1ms
        max-idle: 8
        min-idle: 0

  # Servlet配置
  servlet:
    multipart:
      enabled: true
      max-file-size: 100MB
      max-request-size: 100MB

  # Jackson配置
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
    default-property-inclusion: non_null

  # Elasticsearch配置
  elasticsearch:
    uris: http://localhost:9200
    connection-timeout: 10s
    socket-timeout: 30s

# MyBatis Plus配置
mybatis-plus:
  mapper-locations: classpath*:/mapper/**/*.xml
  type-aliases-package: com.knowledge.base.document.entity
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
    log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl
  global-config:
    db-config:
      id-type: input
      logic-delete-field: deleted
      logic-delete-value: 1
      logic-not-delete-value: 0

# 日志配置
logging:
  level:
    root: INFO
    com.knowledge.base: DEBUG
    com.baomidou.mybatisplus: DEBUG
  pattern:
    console: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n"

# 文件存储配置
file:
  upload:
    path: /data/knowledge-base/uploads
    allowed-types:
      - pdf
      - doc
      - docx
      - xls
      - xlsx
      - ppt
      - pptx
      - txt
      - md
    max-size: 104857600

# Swagger配置
knife4j:
  enable: true
  setting:
    language: zh_cn
  production: false

六、核心功能实现

6.1 文档实体类

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

package com.knowledge.base.document.entity;

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_document")
public class Document extends BaseEntity {

    /**
     * 文档标题
     */
    private String title;

    /**
     * 文档摘要
     */
    private String summary;

    /**
     * 文档内容
     */
    private String content;

    /**
     * 文档类型(1-文章,2-文件)
     */
    private Integer documentType;

    /**
     * 文件路径
     */
    private String filePath;

    /**
     * 文件大小(字节)
     */
    private Long fileSize;

    /**
     * 文件扩展名
     */
    private String fileExtension;

    /**
     * MIME类型
     */
    private String mimeType;

    /**
     * 分类ID
     */
    private Long categoryId;

    /**
     * 标签(逗号分隔)
     */
    private String tags;

    /**
     * 状态(0-草稿,1-已发布,2-已归档)
     */
    private Integer status;

    /**
     * 是否置顶(0-否,1-是)
     */
    private Integer isTop;

    /**
     * 是否推荐(0-否,1-是)
     */
    private Integer isRecommend;

    /**
     * 浏览次数
     */
    private Long viewCount;

    /**
     * 点赞次数
     */
    private Long likeCount;

    /**
     * 收藏次数
     */
    private Long favoriteCount;

    /**
     * 评论次数
     */
    private Long commentCount;

    /**
     * 发布时间
     */
    private LocalDateTime publishTime;

    /**
     * 作者ID
     */
    private Long authorId;

    /**
     * 作者名称
     */
    private String authorName;

    /**
     * 封面图URL
     */
    private String coverImage;

    /**
     * 来源(1-原创,2-转载,3-翻译)
     */
    private Integer source;

    /**
     * 来源URL
     */
    private String sourceUrl;

    /**
     * 允许评论(0-否,1-是)
     */
    private Integer allowComment;

    /**
     * 排序
     */
    private Integer sort;

    /**
     * 备注
     */
    private String remark;
}

6.2 文档DTO

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

package com.knowledge.base.document.dto;

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

import java.io.Serializable;

/**
 * 文档DTO
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Schema(description = "文档信息请求参数")
public class DocumentDTO implements Serializable {

    private static final long serialVersionUID = 1L;

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

    @Schema(description = "文档标题", required = true)
    @NotBlank(message = "文档标题不能为空")
    @Size(max = 200, message = "文档标题长度不能超过200个字符")
    private String title;

    @Schema(description = "文档摘要")
    @Size(max = 500, message = "文档摘要长度不能超过500个字符")
    private String summary;

    @Schema(description = "文档内容")
    private String content;

    @Schema(description = "文档类型(1-文章,2-文件)")
    private Integer documentType;

    @Schema(description = "分类ID")
    private Long categoryId;

    @Schema(description = "标签(逗号分隔)")
    @Size(max = 200, message = "标签长度不能超过200个字符")
    private String tags;

    @Schema(description = "状态(0-草稿,1-已发布,2-已归档)")
    private Integer status;

    @Schema(description = "是否置顶(0-否,1-是)")
    private Integer isTop;

    @Schema(description = "是否推荐(0-否,1-是)")
    private Integer isRecommend;

    @Schema(description = "封面图URL")
    @Size(max = 500, message = "封面图URL长度不能超过500个字符")
    private String coverImage;

    @Schema(description = "来源(1-原创,2-转载,3-翻译)")
    private Integer source;

    @Schema(description = "来源URL")
    @Size(max = 500, message = "来源URL长度不能超过500个字符")
    private String sourceUrl;

    @Schema(description = "允许评论(0-否,1-是)")
    private Integer allowComment;

    @Schema(description = "排序")
    private Integer sort;

    @Schema(description = "备注")
    @Size(max = 500, message = "备注长度不能超过500个字符")
    private String remark;
}

6.3 文档VO

创建 kb-document/src/main/java/com/knowledge/base/document/vo/DocumentVO.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;

/**
 * 文档响应VO
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Schema(description = "文档信息响应")
public class DocumentVO implements Serializable {

    private static final long serialVersionUID = 1L;

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

    @Schema(description = "文档标题")
    private String title;

    @Schema(description = "文档摘要")
    private String summary;

    @Schema(description = "文档内容")
    private String content;

    @Schema(description = "文档类型")
    private Integer documentType;

    @Schema(description = "文件路径")
    private String filePath;

    @Schema(description = "文件大小")
    private Long fileSize;

    @Schema(description = "文件扩展名")
    private String fileExtension;

    @Schema(description = "分类ID")
    private Long categoryId;

    @Schema(description = "分类名称")
    private String categoryName;

    @Schema(description = "标签列表")
    private String tags;

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

    @Schema(description = "是否置顶")
    private Integer isTop;

    @Schema(description = "是否推荐")
    private Integer isRecommend;

    @Schema(description = "浏览次数")
    private Long viewCount;

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

    @Schema(description = "收藏次数")
    private Long favoriteCount;

    @Schema(description = "评论次数")
    private Long commentCount;

    @Schema(description = "发布时间")
    private LocalDateTime publishTime;

    @Schema(description = "作者ID")
    private Long authorId;

    @Schema(description = "作者名称")
    private String authorName;

    @Schema(description = "封面图URL")
    private String coverImage;

    @Schema(description = "来源")
    private Integer source;

    @Schema(description = "来源URL")
    private String sourceUrl;

    @Schema(description = "允许评论")
    private Integer allowComment;

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

    @Schema(description = "更新时间")
    private LocalDateTime updateTime;
}

6.4 文档Mapper

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

package com.knowledge.base.document.mapper;

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

/**
 * 文档Mapper接口
 *
 * @author 苏三
 * @since 1.0.0
 */
@Mapper
public interface DocumentMapper extends BaseMapper<Document> {

    /**
     * 增加浏览次数
     *
     * @param documentId 文档ID
     * @return 影响行数
     */
    int incrementViewCount(@Param("documentId") Long documentId);

    /**
     * 增加点赞次数
     *
     * @param documentId 文档ID
     * @return 影响行数
     */
    int incrementLikeCount(@Param("documentId") Long documentId);

    /**
     * 增加收藏次数
     *
     * @param documentId 文档ID
     * @return 影响行数
     */
    int incrementFavoriteCount(@Param("documentId") Long documentId);

    /**
     * 增加评论次数
     *
     * @param documentId 文档ID
     * @return 影响行数
     */
    int incrementCommentCount(@Param("documentId") Long documentId);
}

创建 kb-document/src/main/resources/mapper/DocumentMapper.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.DocumentMapper">

    <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="incrementFavoriteCount">
        UPDATE kb_document
        SET collect_count = collect_count + 1
        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>
</mapper>

6.5 文档Service

创建接口 kb-document/src/main/java/com/knowledge/base/document/service/DocumentService.java:

package com.knowledge.base.document.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.knowledge.base.document.dto.DocumentDTO;
import com.knowledge.base.document.entity.Document;
import com.knowledge.base.document.vo.DocumentVO;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文档Service接口
 *
 * @author 苏三
 * @since 1.0.0
 */
public interface DocumentService extends IService<Document> {

    /**
     * 创建文档
     *
     * @param documentDTO 文档信息
     * @return 文档ID
     */
    Long createDocument(DocumentDTO documentDTO);

    /**
     * 更新文档
     *
     * @param documentDTO 文档信息
     * @return 是否成功
     */
    Boolean updateDocument(DocumentDTO documentDTO);

    /**
     * 删除文档
     *
     * @param documentId 文档ID
     * @return 是否成功
     */
    Boolean deleteDocument(Long documentId);

    /**
     * 根据ID查询文档
     *
     * @param documentId 文档ID
     * @return 文档信息
     */
    DocumentVO getDocumentById(Long documentId);

    /**
     * 浏览文档(增加浏览次数)
     *
     * @param documentId 文档ID
     * @return 文档信息
     */
    DocumentVO viewDocument(Long documentId);

    /**
     * 分页查询文档列表
     *
     * @param current    当前页
     * @param size       每页大小
     * @param categoryId 分类ID
     * @param keyword    搜索关键词
     * @param status     状态
     * @return 文档分页信息
     */
    IPage<DocumentVO> pageDocuments(Long current, Long size, Long categoryId, String keyword, Integer status);

    /**
     * 上传文档文件
     *
     * @param file 文件
     * @return 文件路径
     */
    String uploadDocumentFile(MultipartFile file);

    /**
     * 点赞文档
     *
     * @param documentId 文档ID
     * @return 是否成功
     */
    Boolean likeDocument(Long documentId);

    /**
     * 收藏文档
     *
     * @param documentId 文档ID
     * @return 是否成功
     */
    Boolean favoriteDocument(Long documentId);

    /**
     * 发布文档
     *
     * @param documentId 文档ID
     * @return 是否成功
     */
    Boolean publishDocument(Long documentId);

    /**
     * 归档文档
     *
     * @param documentId 文档ID
     * @return 是否成功
     */
    Boolean archiveDocument(Long documentId);
}

创建实现类 kb-document/src/main/java/com/knowledge/base/document/service/impl/DocumentServiceImpl.java:

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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
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.ResultCode;
import com.knowledge.base.common.utils.SnowflakeIdGenerator;
import com.knowledge.base.document.dto.DocumentDTO;
import com.knowledge.base.document.entity.Document;
import com.knowledge.base.document.mapper.DocumentMapper;
import com.knowledge.base.document.service.DocumentService;
import com.knowledge.base.document.vo.DocumentVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 文档Service实现类
 *
 * @author 苏三
 * @since 1.0.0
 */
@Slf4j
@Service
public class DocumentServiceImpl extends ServiceImpl<DocumentMapper, Document> implements DocumentService {

    @Resource
    private DocumentMapper documentMapper;

    @Value("${file.upload.path:/data/knowledge-base/uploads}")
    private String uploadPath;

    @Value("${file.upload.max-size:104857600}")
    private Long maxFileSize;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createDocument(DocumentDTO documentDTO) {
        log.info("创建文档:title={}", documentDTO.getTitle());

        // 构建文档实体
        Document document = new Document();
        BeanUtil.copyProperties(documentDTO, document);

        // 生成ID
        document.setId(SnowflakeIdGenerator.getInstance().nextId());

        // 设置默认值
        if (document.getDocumentType() == null) {
            document.setDocumentType(1);
        }
        if (document.getStatus() == null) {
            document.setStatus(0);
        }
        if (document.getIsTop() == null) {
            document.setIsTop(0);
        }
        if (document.getIsRecommend() == null) {
            document.setIsRecommend(0);
        }
        if (document.getSource() == null) {
            document.setSource(1);
        }
        if (document.getAllowComment() == null) {
            document.setAllowComment(1);
        }
        if (document.getSort() == null) {
            document.setSort(0);
        }
        if (document.getViewCount() == null) {
            document.setViewCount(0L);
        }
        if (document.getLikeCount() == null) {
            document.setLikeCount(0L);
        }
        if (document.getFavoriteCount() == null) {
            document.setFavoriteCount(0L);
        }
        if (document.getCommentCount() == null) {
            document.setCommentCount(0L);
        }

        // TODO: 从上下文中获取当前登录用户
        document.setAuthorId(1L);
        document.setAuthorName("系统管理员");

        // 如果是发布状态,设置发布时间
        if (Objects.equals(document.getStatus(), 1)) {
            document.setPublishTime(LocalDateTime.now());
        }

        // 保存文档
        int count = documentMapper.insert(document);
        if (count <= 0) {
            throw new BusinessException("创建文档失败");
        }

        return document.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateDocument(DocumentDTO documentDTO) {
        log.info("更新文档:documentId={}", documentDTO.getId());

        if (documentDTO.getId() == null) {
            throw new BusinessException("文档ID不能为空");
        }

        // 检查文档是否存在
        Document existDocument = documentMapper.selectById(documentDTO.getId());
        if (existDocument == null) {
            throw new BusinessException(ResultCode.DOCUMENT_NOT_EXIST);
        }

        // 构建更新实体
        Document document = new Document();
        BeanUtil.copyProperties(documentDTO, document);

        // 如果状态从草稿变为发布,设置发布时间
        if (Objects.equals(existDocument.getStatus(), 0)
            && Objects.equals(documentDTO.getStatus(), 1)) {
            document.setPublishTime(LocalDateTime.now());
        }

        int count = documentMapper.updateById(document);
        return count > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteDocument(Long documentId) {
        log.info("删除文档:documentId={}", documentId);

        if (documentId == null) {
            throw new BusinessException("文档ID不能为空");
        }

        int count = documentMapper.deleteById(documentId);
        return count > 0;
    }

    @Override
    public DocumentVO getDocumentById(Long documentId) {
        Document document = documentMapper.selectById(documentId);
        if (document == null) {
            throw new BusinessException(ResultCode.DOCUMENT_NOT_EXIST);
        }

        return BeanUtil.copyProperties(document, DocumentVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DocumentVO viewDocument(Long documentId) {
        Document document = documentMapper.selectById(documentId);
        if (document == null) {
            throw new BusinessException(ResultCode.DOCUMENT_NOT_EXIST);
        }

        // 增加浏览次数
        documentMapper.incrementViewCount(documentId);

        return BeanUtil.copyProperties(document, DocumentVO.class);
    }

    @Override
    public IPage<DocumentVO> pageDocuments(Long current, Long size, Long categoryId, String keyword, Integer status) {
        // 构建查询条件
        LambdaQueryWrapper<Document> wrapper = new LambdaQueryWrapper<>();

        if (categoryId != null) {
            wrapper.eq(Document::getCategoryId, categoryId);
        }

        if (status != null) {
            wrapper.eq(Document::getStatus, status);
        }

        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like(Document::getTitle, keyword)
                .or()
                .like(Document::getSummary, keyword)
                .or()
                .like(Document::getContent, keyword)
                .or()
                .like(Document::getTags, keyword));
        }

        // 按置顶和排序排序
        wrapper.orderByDesc(Document::getIsTop)
            .orderByDesc(Document::getSort)
            .orderByDesc(Document::getPublishTime);

        // 分页查询
        Page<Document> page = new Page<>(current, size);
        IPage<Document> documentPage = documentMapper.selectPage(page, wrapper);

        // 转换为VO
        return documentPage.convert(document -> BeanUtil.copyProperties(document, DocumentVO.class));
    }

    @Override
    public String uploadDocumentFile(MultipartFile file) {
        log.info("上传文档文件:fileName={}", file.getOriginalFilename());

        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            throw new BusinessException("文件不能为空");
        }

        // 检查文件大小
        if (file.getSize() > maxFileSize) {
            throw new BusinessException(ResultCode.FILE_SIZE_EXCEEDED);
        }

        // 获取原始文件名和扩展名
        String originalFilename = file.getOriginalFilename();
        String extension = FileUtil.extName(originalFilename);

        // 检查文件类型
        if (!StrUtil.isNotBlank(extension)) {
            throw new BusinessException(ResultCode.FILE_TYPE_NOT_SUPPORTED);
        }

        try {
            // 生成唯一文件名
            String fileName = IdUtil.simpleUUID() + "." + extension;

            // 创建上传目录
            String datePath = LocalDateTime.now().toLocalDate().toString();
            String fullPath = uploadPath + File.separator + datePath;
            File dir = new File(fullPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 保存文件
            File destFile = new File(fullPath, fileName);
            file.transferTo(destFile);

            // 返回相对路径
            return datePath + File.separator + fileName;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new BusinessException(ResultCode.FILE_UPLOAD_FAILED);
        }
    }

    @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);
        }

        // TODO: 检查用户是否已点赞

        // 增加点赞次数
        int count = documentMapper.incrementLikeCount(documentId);
        return count > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean favoriteDocument(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);
        }

        // TODO: 检查用户是否已收藏

        // 增加收藏次数
        int count = documentMapper.incrementFavoriteCount(documentId);
        return count > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean publishDocument(Long documentId) {
        log.info("发布文档:documentId={}", documentId);

        if (documentId == null) {
            throw new BusinessException("文档ID不能为空");
        }

        Document document = new Document();
        document.setId(documentId);
        document.setStatus(1);
        document.setPublishTime(LocalDateTime.now());

        int count = documentMapper.updateById(document);
        return count > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean archiveDocument(Long documentId) {
        log.info("归档文档:documentId={}", documentId);

        if (documentId == null) {
            throw new BusinessException("文档ID不能为空");
        }

        Document document = new Document();
        document.setId(documentId);
        document.setStatus(2);

        int count = documentMapper.updateById(document);
        return count > 0;
    }
}

6.6 文档Controller

创建 kb-document/src/main/java/com/knowledge/base/document/controller/DocumentController.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.DocumentDTO;
import com.knowledge.base.document.service.DocumentService;
import com.knowledge.base.document.vo.DocumentVO;
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.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文档Controller
 *
 * @author 苏三
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/documents")
@Tag(name = "文档管理", description = "文档信息管理接口")
public class DocumentController {

    @Resource
    private DocumentService documentService;

    /**
     * 创建文档
     *
     * @param documentDTO 文档信息
     * @return 文档ID
     */
    @PostMapping
    @Operation(summary = "创建文档", description = "创建新文档")
    public Result<Long> createDocument(@Valid @RequestBody DocumentDTO documentDTO) {
        log.info("创建文档请求:title={}", documentDTO.getTitle());

        Long documentId = documentService.createDocument(documentDTO);
        return Result.success("创建文档成功", documentId);
    }

    /**
     * 更新文档
     *
     * @param documentDTO 文档信息
     * @return 是否成功
     */
    @PutMapping
    @Operation(summary = "更新文档", description = "更新文档信息")
    public Result<Boolean> updateDocument(@Valid @RequestBody DocumentDTO documentDTO) {
        log.info("更新文档请求:documentId={}", documentDTO.getId());

        Boolean success = documentService.updateDocument(documentDTO);
        return Result.success("更新文档成功", success);
    }

    /**
     * 删除文档
     *
     * @param documentId 文档ID
     * @return 是否成功
     */
    @DeleteMapping("/{documentId}")
    @Operation(summary = "删除文档", description = "根据文档ID删除文档")
    public Result<Boolean> deleteDocument(
        @Parameter(description = "文档ID", required = true)
        @PathVariable Long documentId) {
        log.info("删除文档请求:documentId={}", documentId);

        Boolean success = documentService.deleteDocument(documentId);
        return Result.success("删除文档成功", success);
    }

    /**
     * 根据ID查询文档
     *
     * @param documentId 文档ID
     * @return 文档信息
     */
    @GetMapping("/{documentId}")
    @Operation(summary = "查询文档", description = "根据文档ID查询文档详情")
    public Result<DocumentVO> getDocumentById(
        @Parameter(description = "文档ID", required = true)
        @PathVariable Long documentId) {
        log.info("查询文档请求:documentId={}", documentId);

        DocumentVO documentVO = documentService.getDocumentById(documentId);
        return Result.success(documentVO);
    }

    /**
     * 浏览文档(增加浏览次数)
     *
     * @param documentId 文档ID
     * @return 文档信息
     */
    @GetMapping("/{documentId}/view")
    @Operation(summary = "浏览文档", description = "浏览文档并增加浏览次数")
    public Result<DocumentVO> viewDocument(
        @Parameter(description = "文档ID", required = true)
        @PathVariable Long documentId) {
        log.info("浏览文档请求:documentId={}", documentId);

        DocumentVO documentVO = documentService.viewDocument(documentId);
        return Result.success(documentVO);
    }

    /**
     * 分页查询文档列表
     *
     * @param current    当前页
     * @param size       每页大小
     * @param categoryId 分类ID
     * @param keyword    搜索关键词
     * @param status     状态
     * @return 文档分页信息
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询文档", description = "分页查询文档列表")
    public Result<IPage<DocumentVO>> pageDocuments(
        @Parameter(description = "当前页") @RequestParam(defaultValue = "1") Long current,
        @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Long size,
        @Parameter(description = "分类ID") @RequestParam(required = false) Long categoryId,
        @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword,
        @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        log.info("分页查询文档请求:current={}, size={}, categoryId={}, keyword={}, status={}",
            current, size, categoryId, keyword, status);

        IPage<DocumentVO> page = documentService.pageDocuments(current, size, categoryId, keyword, status);
        return Result.success(page);
    }

    /**
     * 上传文档文件
     *
     * @param file 文件
     * @return 文件路径
     */
    @PostMapping("/upload")
    @Operation(summary = "上传文档文件", description = "上传文档文件并返回文件路径")
    public Result<String> uploadDocumentFile(
        @Parameter(description = "文件", required = true)
        @RequestParam("file") MultipartFile file) {
        log.info("上传文档文件请求:fileName={}", file.getOriginalFilename());

        String filePath = documentService.uploadDocumentFile(file);
        return Result.success("上传文件成功", filePath);
    }

    /**
     * 点赞文档
     *
     * @param documentId 文档ID
     * @return 是否成功
     */
    @PostMapping("/{documentId}/like")
    @Operation(summary = "点赞文档", description = "用户点赞文档")
    public Result<Boolean> likeDocument(
        @Parameter(description = "文档ID", required = true)
        @PathVariable Long documentId) {
        log.info("点赞文档请求:documentId={}", documentId);

        Boolean success = documentService.likeDocument(documentId);
        return Result.success("点赞成功", success);
    }

    /**
     * 收藏文档
     *
     * @param documentId 文档ID
     * @return 是否成功
     */
    @PostMapping("/{documentId}/favorite")
    @Operation(summary = "收藏文档", description = "用户收藏文档")
    public Result<Boolean> favoriteDocument(
        @Parameter(description = "文档ID", required = true)
        @PathVariable Long documentId) {
        log.info("收藏文档请求:documentId={}", documentId);

        Boolean success = documentService.favoriteDocument(documentId);
        return Result.success("收藏成功", success);
    }

    /**
     * 发布文档
     *
     * @param documentId 文档ID
     * @return 是否成功
     */
    @PutMapping("/{documentId}/publish")
    @Operation(summary = "发布文档", description = "发布文档")
    public Result<Boolean> publishDocument(
        @Parameter(description = "文档ID", required = true)
        @PathVariable Long documentId) {
        log.info("发布文档请求:documentId={}", documentId);

        Boolean success = documentService.publishDocument(documentId);
        return Result.success("发布成功", success);
    }

    /**
     * 归档文档
     *
     * @param documentId 文档ID
     * @return 是否成功
     */
    @PutMapping("/{documentId}/archive")
    @Operation(summary = "归档文档", description = "归档文档")
    public Result<Boolean> archiveDocument(
        @Parameter(description = "文档ID", required = true)
        @PathVariable Long documentId) {
        log.info("归档文档请求:documentId={}", documentId);

        Boolean success = documentService.archiveDocument(documentId);
        return Result.success("归档成功", success);
    }
}

七、其他核心功能

由于篇幅限制,其他功能的实现方式与文档管理类似,在后面分享。

包括:

7.1 分类管理

  • 实体: Category.java
  • DTO: CategoryDTO.java
  • VO: CategoryVO.java
  • Service: CategoryService.java
  • Controller: CategoryController.java

7.2 标签管理

  • 实体: Tag.java
  • DTO: TagCreateDTO.java, TagUpdateDTO.java, TagQueryDTO.java
  • VO: TagVO.java
  • Service: TagService.java
  • Controller: TagController.java

7.3 评论管理

  • 实体: Comment.java
  • DTO: CommentCreateDTO.java, CommentQueryDTO.java
  • VO: CommentVO.java
  • Service: CommentService.java
  • Controller: CommentController.java

7.4 版本管理

  • 实体: DocumentVersion.java
  • DTO: DocumentVersionRestoreDTO.java
  • VO: DocumentVersionVO.java
  • Service: DocumentVersionService.java
  • Controller: DocumentVersionController.java

7.5 审核管理

  • 实体: DocumentReview.java
  • DTO: DocumentReviewDTO.java, ReviewQueryDTO.java
  • VO: DocumentReviewVO.java
  • Service: DocumentReviewService.java
  • Controller: DocumentReviewController.java

八、测试验证

8.1 执行数据库初始化脚本

# 创建数据库
mysql -u root -p -e "CREATE DATABASE kb_document DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"

# 执行建表脚本
mysql -u root -p kb_document < sql/02_kb_document.sql

# 验证表是否创建成功
mysql -u root -p kb_document -e "SHOW TABLES;"

8.2 启动服务

# 方式一:使用Maven启动
cd kb-document
mvn spring-boot:run

# 方式二:使用IDE启动
# 在IDEA中打开DocumentApplication.java,点击运行

启动成功后,控制台输出:

========================================
   文档服务启动成功!
   Swagger文档地址: http://localhost:8082/api/document/doc.html
========================================

8.3 访问API文档

打开浏览器访问:http://localhost:8082/api/document/doc.html

8.4 测试接口

创建文档

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,
    "categoryId": 1,
    "tags": "Spring Boot,Java,后端开发",
    "status": 1,
    "allowComment": 1
  }'

查询文档列表

curl "http://localhost:8082/api/document/documents/page?current=1&size=10"

查询文档详情

curl "http://localhost:8082/api/document/documents/1"

上传文件

curl -X POST http://localhost:8082/api/document/documents/upload \
  -F "file=@/path/to/document.pdf"

九、总结

本文详细介绍了文档服务模块的搭建过程,涵盖了以下核心内容:

已完成功能

模块功能说明
文档管理CRUD、发布、归档、搜索完整的文档生命周期管理
分类管理树形分类、父子关系灵活的文档分类组织
标签管理标签CRUD、关联管理多维度文档标记
评论管理评论、回复、点赞用户互动交流
版本管理版本历史、版本对比文档版本控制
审核管理审核流程、审核记录内容质量保证
文件上传多格式文件支持Office、PDF等文件
最后修改:2026 年 10 月 24 日
如果觉得我的文章对你有用,请随意赞赏