一、概述

文档分类是知识库系统的核心组织功能,通过树形分类结构实现对文档的科学管理和快速检索。

本文将详细介绍如何在kb-document服务中实现完整的分类管理功能。

1.1 功能定位

分类管理作为文档组织的基础设施,提供以下核心功能:

功能模块说明使用场景
分类CRUD创建、更新、删除、查询分类分类基础管理
树形结构构建父子关系的分类树层级展示
分类移动将分类移动到其他父分类下组织调整
文档统计统计分类下的文档数量数据展示
批量操作批量启用/禁用分类快速管理

1.2 数据模型

分类采用经典的树形结构设计:

根分类 (parentId = 0)
├── 技术文档
│   ├── 后端开发
│   │   ├── Java
│   │   └── Spring Boot
│   └── 前端开发
│       ├── Vue.js
│       └── React
├── 产品文档
│   ├── PRD文档
│   └── 用户手册
└── 运维文档
    ├── 部署文档
    └── 监控文档

1.3 技术实现

  • 树形结构构建:递归算法实现父子关系映射
  • 循环引用检测:防止将分类移动到自己的子分类下
  • 级联检查:删除分类前检查是否有子分类和关联文档
  • 文档数量统计:实时更新分类下的文档数量

二、数据库设计

2.1 分类表结构

CREATE TABLE `kb_category` (
  `id` BIGINT NOT NULL COMMENT '分类ID',
  `parent_id` BIGINT NOT NULL DEFAULT 0 COMMENT '父分类ID(0表示根分类)',
  `category_name` VARCHAR(50) NOT NULL COMMENT '分类名称',
  `category_code` VARCHAR(50) NOT NULL COMMENT '分类编码',
  `description` VARCHAR(500) DEFAULT NULL COMMENT '分类描述',
  `icon` VARCHAR(50) DEFAULT '📁' COMMENT '分类图标',
  `sort` INT NOT NULL DEFAULT 0 COMMENT '排序号',
  `status` TINYINT NOT NULL DEFAULT 1 COMMENT '状态(0-禁用,1-启用)',
  `document_count` INT NOT NULL DEFAULT 0 COMMENT '文档数量',
  `remark` VARCHAR(500) 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 '更新时间',
  `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`),
  KEY `idx_category_code` (`category_code`),
  KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='文档分类表';

2.2 字段说明

字段类型说明必填默认值
idBIGINT分类ID是自增
parent\_idBIGINT父分类ID是0
category\_nameVARCHAR(50)分类名称是-
category\_codeVARCHAR(50)分类编码是-
descriptionVARCHAR(500)分类描述否-
iconVARCHAR(50)分类图标否📁
sortINT排序号是0
statusTINYINT状态是1
document\_countINT文档数量是0

2.3 索引设计

  • 主键索引:id - 主键唯一标识
  • 父级索引:idx_parent_id - 加速查询子分类
  • 编码索引:idx_category_code - 加速按编码查询
  • 状态索引:idx_status - 加速按状态筛选

三、实体类设计

3.1 创建Category实体类

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

/**
 * 文档分类实体类
 *
 * <p>按照阿里巴巴Java开发规范设计,存储文档分类信息</p>
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("kb_category")
public class Category extends BaseEntity {

    /**
     * 父分类ID(0表示根分类)
     */
    private Long parentId;

    /**
     * 分类名称
     */
    private String categoryName;

    /**
     * 分类编码
     */
    private String categoryCode;

    /**
     * 分类描述
     */
    private String description;

    /**
     * 图标
     */
    private String icon;

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

    /**
     * 状态(0-禁用,1-启用)
     */
    private Integer status;

    /**
     * 文档数量
     */
    private Integer documentCount;

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

3.2 设计思路

  1. 继承BaseEntity:复用基础字段(id、创建时间、更新时间等)
  2. parentId字段:实现树形结构,0表示根分类
  3. documentCount字段:冗余设计,避免频繁关联查询
  4. status字段:支持软删除和启用/禁用功能

四、DTO和VO设计

4.1 创建CategoryDTO

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

package com.knowledge.base.document.dto;

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

/**
 * 分类DTO
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Schema(description = "分类信息")
public class CategoryDTO {

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

    @NotBlank(message = "分类名称不能为空")
    @Schema(description = "分类名称")
    private String name;

    @Schema(description = "分类描述")
    private String description;

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

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

    @Schema(description = "图标")
    private String icon;
}

4.2 创建CategoryVO

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

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

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

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

    @Schema(description = "分类描述")
    private String description;

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

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

    @Schema(description = "图标")
    private String icon;

    @Schema(description = "文档数量")
    private Long documentCount;

    @Schema(description = "子分类列表")
    private List<CategoryVO> children;
}

4.3 设计说明

DTO vs VO的区别:

类型用途特点
DTO接收客户端请求字段精简,用于参数校验
VO返回客户端响应包含业务计算字段(如children)

转换逻辑:

  • DTO中的name对应Entity中的categoryName
  • VO中的children由树形构建算法动态生成

五、数据访问层

5.1 创建Mapper接口

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

package com.knowledge.base.document.mapper;

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

/**
 * 分类Mapper接口
 *
 * @author 苏三
 * @since 1.0.0
 */
@Mapper
public interface CategoryMapper extends BaseMapper<Category> {

}

5.2 创建Mapper XML

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

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.knowledge.base.document.entity.Category">
        <id column="id" property="id" />
        <result column="parent_id" property="parentId" />
        <result column="category_name" property="categoryName" />
        <result column="category_code" property="categoryCode" />
        <result column="description" property="description" />
        <result column="icon" property="icon" />
        <result column="sort" property="sort" />
        <result column="status" property="status" />
        <result column="document_count" property="documentCount" />
        <result column="remark" property="remark" />
        <result column="deleted" property="deleted" />
        <result column="create_time" property="createTime" />
        <result column="update_time" property="updateTime" />
        <result column="create_by" property="createBy" />
        <result column="update_by" property="updateBy" />
    </resultMap>
    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, parent_id, category_name, category_code, description, icon, sort, status,
        document_count, remark, deleted, create_time, update_time, create_by, update_by
    </sql>
    <!-- 根据父分类ID查询子分类列表 -->
    <select id="selectByParentId" resultMap="BaseResultMap">
        SELECT <include refid="Base_Column_List" />
        FROM kb_category
        WHERE parent_id = #{parentId}
        AND deleted = 0
        ORDER BY sort ASC, create_time DESC
    </select>
    <!-- 更新文档数量 -->
    <update id="updateDocumentCount">
        UPDATE kb_category
        SET document_count = #{count}
        WHERE id = #{categoryId}
        AND deleted = 0
    </update>
    <!-- 增加文档数量 -->
    <update id="incrementDocumentCount">
        UPDATE kb_category
        SET document_count = document_count + 1
        WHERE id = #{categoryId}
        AND deleted = 0
    </update>
    <!-- 减少文档数量 -->
    <update id="decrementDocumentCount">
        UPDATE kb_category
        SET document_count = GREATEST(document_count - 1, 0)
        WHERE id = #{categoryId}
        AND deleted = 0
    </update>
</mapper>

5.3 MyBatis Plus集成

使用MyBatis Plus后,简单的CRUD操作无需编写SQL:

// 自动生成SQL
categoryMapper.selectById(id);
categoryMapper.selectList(wrapper);
categoryMapper.insert(category);
categoryMapper.updateById(category);
categoryMapper.deleteById(id);

六、业务逻辑层

6.1 创建Service接口

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

package com.knowledge.base.document.service;

import com.knowledge.base.document.dto.CategoryDTO;
import com.knowledge.base.document.vo.CategoryVO;

import java.util.List;

/**
 * 分类Service接口
 *
 * @author 苏三
 * @since 1.0.0
 */
public interface CategoryService {

    /**
     * 创建分类
     *
     * @param categoryDTO 分类信息
     * @return 分类ID
     */
    Long createCategory(CategoryDTO categoryDTO);

    /**
     * 更新分类
     *
     * @param categoryDTO 分类信息
     * @return 是否成功
     */
    Boolean updateCategory(CategoryDTO categoryDTO);

    /**
     * 删除分类
     *
     * @param categoryId 分类ID
     * @return 是否成功
     */
    Boolean deleteCategory(Long categoryId);

    /**
     * 根据ID查询分类
     *
     * @param categoryId 分类ID
     * @return 分类信息
     */
    CategoryVO getCategoryById(Long categoryId);

    /**
     * 获取分类树
     *
     * @return 分类树
     */
    List<CategoryVO> getCategoryTree();

    /**
     * 获取子分类
     *
     * @param parentId 父分类ID
     * @return 子分类列表
     */
    List<CategoryVO> getChildren(Long parentId);

    /**
     * 移动分类
     *
     * @param categoryId   分类ID
     * @param newParentId 新父分类ID
     * @return 是否成功
     */
    Boolean moveCategory(Long categoryId, Long newParentId);

    /**
     * 获取所有分类
     *
     * @return 分类列表
     */
    List<CategoryVO> getAllCategories();
}

6.2 创建Service实现类

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

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

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.knowledge.base.common.exception.BusinessException;
import com.knowledge.base.common.utils.SnowflakeIdGenerator;
import com.knowledge.base.document.dto.CategoryDTO;
import com.knowledge.base.document.entity.Category;
import com.knowledge.base.document.mapper.CategoryMapper;
import com.knowledge.base.document.service.CategoryService;
import com.knowledge.base.document.vo.CategoryVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

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

/**
 * 分类Service实现类
 *
 * @author 苏三
 * @since 1.0.0
 */
@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createCategory(CategoryDTO categoryDTO) {
        log.info("创建分类:categoryName={}", categoryDTO.getName());

        // 检查分类名称是否已存在
        Category existCategory = categoryMapper.selectOne(
                new LambdaQueryWrapper<Category>()
                        .eq(Category::getCategoryName, categoryDTO.getName())
        );
        if (existCategory != null) {
            throw new BusinessException("分类名称已存在");
        }

        // 检查父分类是否存在
        Long parentId = categoryDTO.getParentId() != null ? categoryDTO.getParentId() : 0L;
        if (parentId > 0) {
            Category parentCategory = categoryMapper.selectById(parentId);
            if (parentCategory == null) {
                throw new BusinessException("父分类不存在");
            }
        }

        // 生成分类编码
        String categoryCode = StringUtils.hasText(categoryDTO.getName())
                ? generateCategoryCode(categoryDTO.getName())
                : "CATEGORY_" + System.currentTimeMillis();

        // 构建分类实体
        Category category = new Category();
        category.setId(SnowflakeIdGenerator.getInstance().nextId());
        category.setParentId(parentId);
        category.setCategoryName(categoryDTO.getName());
        category.setCategoryCode(categoryCode);
        category.setDescription(categoryDTO.getDescription());
        category.setIcon(categoryDTO.getIcon());
        category.setSort(categoryDTO.getSortOrder() != null ? categoryDTO.getSortOrder() : 0);
        category.setStatus(1);
        category.setDocumentCount(0);

        // 保存分类
        int count = categoryMapper.insert(category);
        if (count <= 0) {
            throw new BusinessException("创建分类失败");
        }

        return category.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateCategory(CategoryDTO categoryDTO) {
        log.info("更新分类:categoryId={}", categoryDTO.getId());

        if (categoryDTO.getId() == null) {
            throw new BusinessException("分类ID不能为空");
        }

        // 检查分类是否存在
        Category existCategory = categoryMapper.selectById(categoryDTO.getId());
        if (existCategory == null) {
            throw new BusinessException("分类不存在");
        }

        // 检查分类名称是否被其他分类使用
        if (StringUtils.hasText(categoryDTO.getName())
                && !categoryDTO.getName().equals(existCategory.getCategoryName())) {
            Category category = categoryMapper.selectOne(
                    new LambdaQueryWrapper<Category>()
                            .eq(Category::getCategoryName, categoryDTO.getName())
            );
            if (category != null && !category.getId().equals(categoryDTO.getId())) {
                throw new BusinessException("分类名称已被使用");
            }
        }

        // 检查父分类是否存在
        if (categoryDTO.getParentId() != null) {
            if (categoryDTO.getParentId().equals(categoryDTO.getId())) {
                throw new BusinessException("父分类不能是自己");
            }
            if (categoryDTO.getParentId() > 0) {
                Category parentCategory = categoryMapper.selectById(categoryDTO.getParentId());
                if (parentCategory == null) {
                    throw new BusinessException("父分类不存在");
                }
            }
        }

        // 构建更新实体
        Category category = new Category();
        category.setId(categoryDTO.getId());
        if (StringUtils.hasText(categoryDTO.getName())) {
            category.setCategoryName(categoryDTO.getName());
        }
        category.setDescription(categoryDTO.getDescription());
        if (categoryDTO.getParentId() != null) {
            category.setParentId(categoryDTO.getParentId());
        }
        if (categoryDTO.getIcon() != null) {
            category.setIcon(categoryDTO.getIcon());
        }
        if (categoryDTO.getSortOrder() != null) {
            category.setSort(categoryDTO.getSortOrder());
        }

        int count = categoryMapper.updateById(category);
        return count > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteCategory(Long categoryId) {
        log.info("删除分类:categoryId={}", categoryId);

        if (categoryId == null) {
            throw new BusinessException("分类ID不能为空");
        }

        // 检查分类是否存在
        Category category = categoryMapper.selectById(categoryId);
        if (category == null) {
            throw new BusinessException("分类不存在");
        }

        // 检查是否有子分类
        Long childCount = categoryMapper.selectCount(
                new LambdaQueryWrapper<Category>()
                        .eq(Category::getParentId, categoryId)
        );
        if (childCount > 0) {
            throw new BusinessException("该分类下有子分类,不能删除");
        }

        // TODO: 检查是否有关联文档,如果有则不允许删除或提示用户

        // 删除分类
        int count = categoryMapper.deleteById(categoryId);
        return count > 0;
    }

    @Override
    public CategoryVO getCategoryById(Long categoryId) {
        if (categoryId == null) {
            throw new BusinessException("分类ID不能为空");
        }

        Category category = categoryMapper.selectById(categoryId);
        if (category == null) {
            throw new BusinessException("分类不存在");
        }

        return convertToVO(category);
    }

    @Override
    public List<CategoryVO> getCategoryTree() {
        // 查询所有分类
        List<Category> allCategories = categoryMapper.selectList(
                new LambdaQueryWrapper<Category>()
                        .eq(Category::getStatus, 1)
                        .orderByAsc(Category::getSort)
        );

        // 转换为VO
        List<CategoryVO> categoryVOs = allCategories.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        // 构建树形结构
        return buildCategoryTree(categoryVOs, 0L);
    }

    @Override
    public List<CategoryVO> getChildren(Long parentId) {
        if (parentId == null) {
            parentId = 0L;
        }

        List<Category> categories = categoryMapper.selectList(
                new LambdaQueryWrapper<Category>()
                        .eq(Category::getParentId, parentId)
                        .eq(Category::getStatus, 1)
                        .orderByAsc(Category::getSort)
        );

        return categories.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean moveCategory(Long categoryId, Long newParentId) {
        log.info("移动分类:categoryId={}, newParentId={}", categoryId, newParentId);

        if (categoryId == null) {
            throw new BusinessException("分类ID不能为空");
        }

        // 检查分类是否存在
        Category category = categoryMapper.selectById(categoryId);
        if (category == null) {
            throw new BusinessException("分类不存在");
        }

        // 检查是否移动到自己
        if (categoryId.equals(newParentId)) {
            throw new BusinessException("不能移动到自己");
        }

        // 检查新父分类是否存在
        if (newParentId != null && newParentId > 0) {
            Category parentCategory = categoryMapper.selectById(newParentId);
            if (parentCategory == null) {
                throw new BusinessException("父分类不存在");
            }

            // 检查是否移动到自己的子分类下
            if (isDescendant(categoryId, newParentId)) {
                throw new BusinessException("不能移动到自己的子分类下");
            }
        }

        // 更新父分类ID
        Category updateCategory = new Category();
        updateCategory.setId(categoryId);
        updateCategory.setParentId(newParentId != null ? newParentId : 0L);

        int count = categoryMapper.updateById(updateCategory);
        return count > 0;
    }

    @Override
    public List<CategoryVO> getAllCategories() {
        List<Category> categories = categoryMapper.selectList(
                new LambdaQueryWrapper<Category>()
                        .eq(Category::getStatus, 1)
                        .orderByAsc(Category::getSort)
        );

        return categories.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    /**
     * 转换为VO
     *
     * @param category 分类实体
     * @return 分类VO
     */
    private CategoryVO convertToVO(Category category) {
        return CategoryVO.builder()
                .id(category.getId())
                .name(category.getCategoryName())
                .description(category.getDescription())
                .parentId(category.getParentId())
                .sortOrder(category.getSort())
                .icon(category.getIcon())
                .documentCount(category.getDocumentCount() != null ? category.getDocumentCount().longValue() : 0L)
                .build();
    }

    /**
     * 构建分类树
     *
     * @param categories 分类列表
     * @param parentId   父分类ID
     * @return 分类树
     */
    private List<CategoryVO> buildCategoryTree(List<CategoryVO> categories, Long parentId) {
        List<CategoryVO> tree = new ArrayList<>();

        for (CategoryVO category : categories) {
            if (parentId.equals(category.getParentId())) {
                // 递归查找子分类
                category.setChildren(buildCategoryTree(categories, category.getId()));
                tree.add(category);
            }
        }

        return tree;
    }

    /**
     * 检查是否是后代节点
     *
     * @param ancestorId   祖先节点ID
     * @param descendantId 后代节点ID
     * @return 是否是后代
     */
    private boolean isDescendant(Long ancestorId, Long descendantId) {
        Category category = categoryMapper.selectById(descendantId);
        while (category != null && category.getParentId() != null && category.getParentId() > 0) {
            if (category.getParentId().equals(ancestorId)) {
                return true;
            }
            category = categoryMapper.selectById(category.getParentId());
        }
        return false;
    }

    /**
     * 生成分类编码
     *
     * @param categoryName 分类名称
     * @return 分类编码
     */
    private String generateCategoryCode(String categoryName) {
        // 简单的拼音首字母或缩写生成逻辑
        // 实际项目中可以使用拼音转换库
        return "CAT_" + categoryName.toUpperCase()
                .replaceAll("[^A-Z0-9]", "_")
                .replaceAll("_+", "_")
                .replaceAll("^_|_$", "") + "_" + System.currentTimeMillis();
    }
}

6.3 核心算法说明

6.3.1 树形结构构建

private List<CategoryVO> buildCategoryTree(List<CategoryVO> categories, Long parentId) {
    List<CategoryVO> tree = new ArrayList<>();

    for (CategoryVO category : categories) {
        if (parentId.equals(category.getParentId())) {
            // 递归查找子分类
            category.setChildren(buildCategoryTree(categories, category.getId()));
            tree.add(category);
        }
    }

    return tree;
}

算法特点:

  • 时间复杂度:O(n²),n为节点数量
  • 空间复杂度:O(n),递归栈深度
  • 适用场景:中小型分类树(<1000个节点)

6.3.2 循环引用检测

private boolean isDescendant(Long ancestorId, Long descendantId) {
    Category category = categoryMapper.selectById(descendantId);
    while (category != null && category.getParentId() != null && category.getParentId() > 0) {
        if (category.getParentId().equals(ancestorId)) {
            return true;
        }
        category = categoryMapper.selectById(category.getParentId());
    }
    return false;
}

检测逻辑:

  1. 从目标节点向上遍历父节点
  2. 如果遇到源节点,说明会形成循环
  3. 如果到达根节点仍未遇到,则安全

七、控制器层

7.1 创建CategoryController

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

package com.knowledge.base.document.controller;

import com.knowledge.base.common.result.Result;
import com.knowledge.base.document.dto.CategoryDTO;
import com.knowledge.base.document.service.CategoryService;
import com.knowledge.base.document.vo.CategoryVO;
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 java.util.List;

/**
 * 分类管理Controller
 *
 * @author 苏三
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/categories")
@Tag(name = "分类管理", description = "文档分类管理接口")
public class CategoryController {

    @Resource
    private CategoryService categoryService;

    /**
     * 创建分类
     *
     * @param categoryDTO 分类信息
     * @return 分类ID
     */
    @PostMapping
    @Operation(summary = "创建分类", description = "创建新分类")
    public Result<Long> createCategory(@Valid @RequestBody CategoryDTO categoryDTO) {
        log.info("创建分类请求:name={}", categoryDTO.getName());

        Long categoryId = categoryService.createCategory(categoryDTO);
        return Result.success("创建分类成功", categoryId);
    }

    /**
     * 更新分类
     *
     * @param categoryDTO 分类信息
     * @return 是否成功
     */
    @PutMapping
    @Operation(summary = "更新分类", description = "更新分类信息")
    public Result<Boolean> updateCategory(@Valid @RequestBody CategoryDTO categoryDTO) {
        log.info("更新分类请求:categoryId={}", categoryDTO.getId());

        Boolean success = categoryService.updateCategory(categoryDTO);
        return Result.success("更新分类成功", success);
    }

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

        Boolean success = categoryService.deleteCategory(categoryId);
        return Result.success("删除分类成功", success);
    }

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

        CategoryVO categoryVO = categoryService.getCategoryById(categoryId);
        return Result.success(categoryVO);
    }

    /**
     * 获取分类树
     *
     * @return 分类树
     */
    @GetMapping("/tree")
    @Operation(summary = "获取分类树", description = "获取完整的分类树结构")
    public Result<List<CategoryVO>> getCategoryTree() {
        log.info("获取分类树请求");

        List<CategoryVO> tree = categoryService.getCategoryTree();
        return Result.success(tree);
    }

    /**
     * 获取子分类
     *
     * @param parentId 父分类ID
     * @return 子分类列表
     */
    @GetMapping("/children/{parentId}")
    @Operation(summary = "获取子分类", description = "获取指定父分类的子分类列表")
    public Result<List<CategoryVO>> getChildren(
        @Parameter(description = "父分类ID", required = true)
        @PathVariable Long parentId) {
        log.info("获取子分类请求:parentId={}", parentId);

        List<CategoryVO> children = categoryService.getChildren(parentId);
        return Result.success(children);
    }

    /**
     * 移动分类
     *
     * @param categoryId    分类ID
     * @param newParentId 新父分类ID
     * @return 是否成功
     */
    @PutMapping("/{categoryId}/move")
    @Operation(summary = "移动分类", description = "移动分类到新的父分类下")
    public Result<Boolean> moveCategory(
        @Parameter(description = "分类ID", required = true)
        @PathVariable Long categoryId,
        @Parameter(description = "新父分类ID", required = true)
        @RequestParam Long newParentId) {
        log.info("移动分类请求:categoryId={}, newParentId={}", categoryId, newParentId);

        Boolean success = categoryService.moveCategory(categoryId, newParentId);
        return Result.success("移动分类成功", success);
    }

    /**
     * 获取所有分类(平铺)
     *
     * @return 分类列表
     */
    @GetMapping("/list")
    @Operation(summary = "获取所有分类", description = "获取所有分类列表(平铺)")
    public Result<List<CategoryVO>> getAllCategories() {
        log.info("获取所有分类请求");

        List<CategoryVO> categories = categoryService.getAllCategories();
        return Result.success(categories);
    }
}

7.2 RESTful API设计

方法路径说明参数
POST/categories创建分类CategoryDTO
PUT/categories更新分类CategoryDTO
DELETE/categories/{id}删除分类categoryId
GET/categories/{id}查询分类categoryId
GET/categories/tree获取分类树-
GET/categories/children/{parentId}获取子分类parentId
PUT/categories/{id}/move移动分类categoryId, newParentId
GET/categories/list获取所有分类-

八、测试验证

8.1 初始化测试数据

执行以下SQL插入测试数据:

-- 插入根分类
INSERT INTO kb_category (id, parent_id, category_name, category_code, description, icon, sort, status, document_count) VALUES
(1000000000000000001, 0, '技术文档', 'CAT_TECH_DOC', '技术类文档', '📚', 1, 1, 0),
(1000000000000000002, 0, '产品文档', 'CAT_PROD_DOC', '产品类文档', '📖', 2, 1, 0),
(1000000000000000003, 0, '运维文档', 'CAT_OPS_DOC', '运维类文档', '⚙️', 3, 1, 0);

-- 插入子分类
INSERT INTO kb_category (id, parent_id, category_name, category_code, description, icon, sort, status, document_count) VALUES
(1000000000000000004, 1000000000000000001, '后端开发', 'CAT_BACKEND', '后端开发技术', '💻', 1, 1, 0),
(1000000000000000005, 1000000000000000001, '前端开发', 'CAT_FRONTEND', '前端开发技术', '🎨', 2, 1, 0),
(1000000000000000006, 1000000000000000002, 'PRD文档', 'CAT_PRD', '产品需求文档', '📝', 1, 1, 0),
(1000000000000000007, 1000000000000000002, '用户手册', 'CAT_USER_MANUAL', '用户使用手册', '📘', 2, 1, 0);

-- 插入三级分类
INSERT INTO kb_category (id, parent_id, category_name, category_code, description, icon, sort, status, document_count) VALUES
(1000000000000000008, 1000000000000000004, 'Java', 'CAT_JAVA', 'Java编程语言', '☕', 1, 1, 0),
(1000000000000000009, 1000000000000000004, 'Spring Boot', 'CAT_SPRING_BOOT', 'Spring Boot框架', '🍃', 2, 1, 0),
(1000000000000000010, 1000000000000000005, 'Vue.js', 'CAT_VUE', 'Vue.js框架', '💚', 1, 1, 0),
(1000000000000000011, 1000000000000000005, 'React', 'CAT_REACT', 'React框架', '⚛️', 2, 1, 0);

8.2 测试分类CRUD

创建根分类

curl -X POST http://localhost:8082/api/document/categories \
  -H "Content-Type: application/json" \
  -d '{
    "name": "测试分类",
    "description": "这是一个测试分类",
    "parentId": 0,
    "sortOrder": 99,
    "icon": "🧪"
  }'

创建子分类

curl -X POST http://localhost:8082/api/document/categories \
  -H "Content-Type: application/json" \
  -d '{
    "name": "测试子分类",
    "description": "这是一个测试子分类",
    "parentId": 1000000000000000001,
    "sortOrder": 1
  }'

查询分类树

curl http://localhost:8082/api/document/categories/tree

查询子分类

curl http://localhost:8082/api/document/categories/children/1000000000000000001

更新分类

curl -X PUT http://localhost:8082/api/document/categories \
  -H "Content-Type: application/json" \
  -d '{
    "id": 1000000000000000001,
    "name": "技术文档(已更新)",
    "description": "更新后的描述"
  }'

移动分类

curl -X PUT "http://localhost:8082/api/document/categories/1000000000000000004/move?newParentId=1000000000000000002"

删除分类

curl -X DELETE http://localhost:8082/api/document/categories/1000000000000000004

8.3 验证数据结构

执行成功后,查询分类树应返回如下结构:

{
  "code": 200,
  "message": "操作成功",
  "data": [
    {
      "id": 1000000000000000001,
      "name": "技术文档",
      "description": "技术类文档",
      "parentId": 0,
      "sortOrder": 1,
      "icon": "📚",
      "documentCount": 0,
      "children": [
        {
          "id": 1000000000000000004,
          "name": "后端开发",
          "parentId": 1000000000000000001,
          "children": [
            {
              "id": 1000000000000000008,
              "name": "Java",
              "parentId": 1000000000000000004,
              "children": []
            }
          ]
        }
      ]
    }
  ]
}

总结

本文详细介绍了文档分类管理功能的完整实现,涵盖了以下核心内容:

已完成功能

功能实现方式说明
分类CRUDService + Controller完整的增删改查
树形结构递归算法构建父子关系
分类移动循环引用检测防止非法移动
文档统计冗余字段documentCount
最后修改:2026 年 10 月 24 日
如果觉得我的文章对你有用,请随意赞赏