一、概述

标签是知识库系统中文档的重要补充组织方式,通过标签可以实现文档的灵活分类和多维度检索。

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

1.1 功能定位

标签管理作为文档组织的补充方式,提供以下核心功能:

功能模块说明使用场景
标签CRUD创建、更新、删除、查询标签标签基础管理
热门标签按使用频率排序展示热门内容推荐
分类关联标签与分类关联按分类筛选标签
批量创建批量创建标签快速打标签
标签搜索模糊搜索标签自动补全建议

1.2 标签与分类的区别

特性分类标签
结构树形层级结构扁平结构
数量相对固定,由管理员预先规划动态增长,用户可自由创建
约束一个文档只能有一个主分类一个文档可以有多个标签
用途文档的主要归类和导航文档的多维度标记和交叉检索
管理通常由管理员统一管理用户可自由创建和使用
层级支持多级父子分类无层级,扁平化
查询按分类层级浏览按标签组合搜索
典型场景技术文档(前端/后端/数据库)跨分类标记(Java/新手/重要)

使用建议:

  • 分类:用于文档的主导航,建议建立清晰的2-3级分类体系
  • 标签:用于文档的辅助标记,鼓励用户创建个性化标签进行知识管理

一、概述

标签是知识库系统中文档的重要补充组织方式,通过标签可以实现文档的灵活分类和多维度检索。本文将详细介绍如何在kb-document服务中实现完整的标签管理功能。

1.1 功能定位

标签管理作为文档组织的补充方式,提供以下核心功能:

功能模块说明使用场景
标签CRUD创建、更新、删除、查询标签标签基础管理
热门标签按使用频率排序展示热门内容推荐
分类关联标签与分类关联按分类筛选标签
批量创建批量创建标签快速打标签
标签搜索模糊搜索标签自动补全建议

1.2 标签与分类的区别

特性分类标签
结构树形层级结构扁平结构
数量相对固定动态增长
约束一个文档只能有一个分类一个文档可以有多个标签
用途文档的主要归类文档的多维度标记
管理通常由管理员管理用户可自由创建

1.3 标签类型设计

  • SYSTEM:系统预设标签,如"置顶"、"推荐"、"精选"等
  • USER:用户自定义标签,用户可以根据需要自由创建

二、数据库设计

2.1 标签表结构

CREATE TABLE `tb_tag` (
  `id` BIGINT NOT NULL COMMENT '标签ID',
  `tag_name` VARCHAR(50) NOT NULL COMMENT '标签名称',
  `tag_code` VARCHAR(50) NOT NULL COMMENT '标签编码',
  `category_id` BIGINT DEFAULT NULL COMMENT '所属分类ID',
  `tag_type` TINYINT NOT NULL DEFAULT 1 COMMENT '标签类型:0-SYSTEM,1-用户标签',
  `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-正常',
  `deleted` TINYINT NOT NULL DEFAULT 0 COMMENT '删除标识',
  `version` INT NOT NULL DEFAULT 0 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 '更新人',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_tag_code` (`tag_code`),
  KEY `idx_tag_name` (`tag_name`),
  KEY `idx_category_id` (`category_id`),
  KEY `idx_tag_type` (`tag_type`),
  KEY `idx_status` (`status`),
  KEY `idx_doc_count` (`doc_count`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='标签表';

2.2 文档标签关联表

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`),
  KEY `idx_document_id` (`document_id`),
  KEY `idx_tag_id` (`tag_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='文档标签关联表';

2.3 字段说明

字段类型说明必填默认值
idBIGINT标签ID是自增
tag\_nameVARCHAR(50)标签名称是-
tag\_codeVARCHAR(50)标签编码是-
category\_idBIGINT所属分类ID否-
tag\_typeTINYINT标签类型:0-SYSTEM,1-USER是1
colorVARCHAR(20)标签颜色否-
iconVARCHAR(50)标签图标否-
doc\_countINT文档数量是0
statusTINYINT状态是1

2.4 索引设计

  • 主键索引:id - 主键唯一标识
  • 唯一索引:uk_tag_code - 标签编码唯一
  • 普通索引:idx_tag_name - 加速按名称查询
  • 普通索引:idx_category_id - 加速按分类查询
  • 普通索引:idx_doc_count - 加速按文档数排序

三、实体类设计

3.1 创建Tag实体类

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

package com.knowledge.base.document.entity;

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


/**
 * 标签实体
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("tb_tag")
@Schema(description = "标签实体")
public class Tag extends BaseEntity {

    private static final long serialVersionUID = 1L;

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

    /**
     * 标签名称
     */
    @Schema(description = "标签名称")
    private String tagName;

    /**
     * 标签编码
     */
    @Schema(description = "标签编码")
    private String tagCode;

    /**
     * 所属分类ID
     */
    @Schema(description = "所属分类ID")
    private Long categoryId;

    /**
     * 标签类型:0-SYSTEM,1-用户标签
     */
    @Schema(description = "标签类型")
    private Integer tagType;

    /**
     * 获取标签类型枚举
     *
     * @return 标签类型枚举
     */
    public TagTypeEnum getTagTypeEnum() {
        return TagTypeEnum.of(this.tagType);
    }

    /**
     * 颜色
     */
    @Schema(description = "颜色")
    private String color;

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

    /**
     * 文档数量
     */
    @Schema(description = "文档数量")
    private Integer docCount;

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

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

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

package com.knowledge.base.document.enums;

import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * 标签类型枚举
 *
 * <p>按照阿里巴巴Java开发规范设计,定义标签类型</p>
 *
 * @author 苏三
 * @since 1.0.0
 */
@Getter
@AllArgsConstructor
public enum TagTypeEnum {

    /**
     * 系统标签
     */
    SYSTEM(0, "系统标签"),

    /**
     * 用户标签
     */
    USER(1, "用户标签");

    /**
     * 类型编码
     */
    private final Integer code;

    /**
     * 类型描述
     */
    private final String desc;

    /**
     * 根据编码获取枚举
     *
     * @param code 编码
     * @return 枚举值,找不到返回null
     */
    public static TagTypeEnum of(Integer code) {
        if (code == null) {
            return null;
        }
        for (TagTypeEnum type : values()) {
            if (type.getCode().equals(code)) {
                return type;
            }
        }
        return null;
    }

    /**
     * 根据编码获取枚举,找不到返回默认值USER
     *
     * @param code 编码
     * @return 枚举值
     */
    public static TagTypeEnum ofOrDefault(Integer code) {
        TagTypeEnum type = of(code);
        return type != null ? type : USER;
    }
}

3.2 设计说明

  1. 继承BaseEntity:复用基础字段(创建时间、更新时间等)
  2. tagCode唯一性:使用唯一索引确保标签编码不重复
  3. docCount字段:冗余设计,避免频繁关联查询
  4. tagType字段:区分系统标签和用户标签

四、DTO和VO设计

4.1 创建TagCreateDTO

创建 kb-document/src/main/java/com/knowledge/base/document/dto/TagCreateDTO.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 TagCreateDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 标签名称
     */
    @Schema(description = "标签名称")
    @NotBlank(message = "标签名称不能为空")
    @Size(max = 50, message = "标签名称长度不能超过50个字符")
    private String tagName;

    /**
     * 标签编码
     */
    @Schema(description = "标签编码")
    @Size(max = 50, message = "标签编码长度不能超过50个字符")
    private String tagCode;

    /**
     * 所属分类ID
     */
    @Schema(description = "所属分类ID")
    private Long categoryId;

    /**
     * 标签类型:0-SYSTEM,1-USER
     */
    @Schema(description = "标签类型")
    private Integer tagType;

    /**
     * 颜色
     */
    @Schema(description = "颜色")
    @Size(max = 20, message = "颜色值长度不能超过20个字符")
    private String color;

    /**
     * 图标
     */
    @Schema(description = "图标")
    @Size(max = 50, message = "图标值长度不能超过50个字符")
    private String icon;
}

4.2 创建TagUpdateDTO

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

package com.knowledge.base.document.dto;

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

import java.io.Serializable;

/**
 * 标签更新DTO
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Schema(description = "标签更新请求")
public class TagUpdateDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 标签ID
     */
    @Schema(description = "标签ID")
    @NotNull(message = "标签ID不能为空")
    private Long id;

    /**
     * 标签名称
     */
    @Schema(description = "标签名称")
    @Size(max = 50, message = "标签名称长度不能超过50个字符")
    private String tagName;

    /**
     * 标签编码
     */
    @Schema(description = "标签编码")
    @Size(max = 50, message = "标签编码长度不能超过50个字符")
    private String tagCode;

    /**
     * 所属分类ID
     */
    @Schema(description = "所属分类ID")
    private Long categoryId;

    /**
     * 颜色
     */
    @Schema(description = "颜色")
    @Size(max = 20, message = "颜色值长度不能超过20个字符")
    private String color;

    /**
     * 图标
     */
    @Schema(description = "图标")
    @Size(max = 50, message = "图标值长度不能超过50个字符")
    private String icon;

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

4.3 创建TagQueryDTO

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

package com.knowledge.base.document.dto;

import com.knowledge.base.common.result.PageParam;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * 标签查询DTO
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@EqualsAndHashCode(callSuper = true)
@Schema(description = "标签查询请求")
public class TagQueryDTO extends PageParam {

    private static final long serialVersionUID = 1L;

    /**
     * 标签名称(模糊查询)
     */
    @Schema(description = "标签名称")
    private String tagName;

    /**
     * 标签类型:0-SYSTEM,1-USER
     */
    @Schema(description = "标签类型")
    private Integer tagType;

    /**
     * 所属分类ID
     */
    @Schema(description = "所属分类ID")
    private Long categoryId;

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

4.4 创建TagVO

创建 kb-document/src/main/java/com/knowledge/base/document/vo/TagVO.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.io.Serializable;
import java.time.LocalDateTime;

/**
 * 标签VO
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "标签信息")
public class TagVO implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 标签ID
     */
    @Schema(description = "标签ID")
    private Long id;

    /**
     * 标签名称
     */
    @Schema(description = "标签名称")
    private String tagName;

    /**
     * 标签编码
     */
    @Schema(description = "标签编码")
    private String tagCode;

    /**
     * 所属分类ID
     */
    @Schema(description = "所属分类ID")
    private Long categoryId;

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

    /**
     * 标签类型:0-SYSTEM,1-USER
     */
    @Schema(description = "标签类型")
    private Integer tagType;

    /**
     * 颜色
     */
    @Schema(description = "颜色")
    private String color;

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

    /**
     * 文档数量
     */
    @Schema(description = "文档数量")
    private Integer docCount;

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

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

五、数据访问层

5.1 创建Mapper接口

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

package com.knowledge.base.document.mapper;

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

/**
 * 标签Mapper接口
 *
 * @author 苏三
 * @since 1.0.0
 */
@Mapper
public interface TagMapper extends BaseMapper<Tag> {

}

5.2 创建Mapper XML

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

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.knowledge.base.document.entity.Tag">
        <id column="id" property="id" />
        <result column="tag_name" property="tagName" />
        <result column="tag_code" property="tagCode" />
        <result column="category_id" property="categoryId" />
        <result column="tag_type" property="tagType" />
        <result column="color" property="color" />
        <result column="icon" property="icon" />
        <result column="doc_count" property="docCount" />
        <result column="status" property="status" />
        <result column="deleted" property="deleted" />
        <result column="version" property="version" />
        <result column="create_time" property="createTime" />
        <result column="update_time" property="updateTime" />
        <result column="create_by" property="createBy" />
        <result column="update_by" property="updateBy" />
    </resultMap>
    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, tag_name, tag_code, category_id, tag_type, color, icon, doc_count, status,
        deleted, version, create_time, update_time, create_by, update_by
    </sql>
    <!-- 根据分类ID查询标签列表 -->
    <select id="selectByCategoryId" resultMap="BaseResultMap">
        SELECT <include refid="Base_Column_List" />
        FROM tb_tag
        WHERE category_id = #{categoryId}
        AND deleted = 0
        ORDER BY doc_count DESC
    </select>
    <!-- 根据标签编码查询标签 -->
    <select id="selectByTagCode" resultMap="BaseResultMap">
        SELECT <include refid="Base_Column_List" />
        FROM tb_tag
        WHERE tag_code = #{tagCode}
        AND deleted = 0
        LIMIT 1
    </select>
    <!-- 查询热门标签 -->
    <select id="selectHotTags" resultMap="BaseResultMap">
        SELECT <include refid="Base_Column_List" />
        FROM tb_tag
        WHERE status = 1
        AND deleted = 0
        ORDER BY doc_count DESC
        LIMIT #{limit}
    </select>
    <!-- 更新文档数量 -->
    <update id="updateDocumentCount">
        UPDATE tb_tag
        SET doc_count = #{count}
        WHERE id = #{tagId}
        AND deleted = 0
    </update>
    <!-- 增加文档数量 -->
    <update id="incrementDocumentCount">
        UPDATE tb_tag
        SET doc_count = doc_count + 1
        WHERE id = #{tagId}
        AND deleted = 0
    </update>
    <!-- 减少文档数量 -->
    <update id="decrementDocumentCount">
        UPDATE tb_tag
        SET doc_count = GREATEST(doc_count - 1, 0)
        WHERE id = #{tagId}
        AND deleted = 0
    </update>
    <!-- 模糊搜索标签 -->
    <select id="searchByName" resultMap="BaseResultMap">
        SELECT <include refid="Base_Column_List" />
        FROM tb_tag
        WHERE tag_name LIKE CONCAT('%', #{keyword}, '%')
        AND status = 1
        AND deleted = 0
        ORDER BY doc_count DESC
    </select>
</mapper>

六、业务逻辑层

6.1 创建Service接口

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

package com.knowledge.base.document.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.knowledge.base.common.result.PageResult;
import com.knowledge.base.document.dto.TagCreateDTO;
import com.knowledge.base.document.dto.TagQueryDTO;
import com.knowledge.base.document.dto.TagUpdateDTO;
import com.knowledge.base.document.entity.Tag;
import com.knowledge.base.document.vo.TagVO;

import java.util.List;

/**
 * 标签Service接口
 *
 * @author 苏三
 * @since 1.0.0
 */
public interface TagService extends IService<Tag> {

    /**
     * 创建标签
     *
     * @param dto 创建DTO
     * @return 标签ID
     */
    Long createTag(TagCreateDTO dto);

    /**
     * 更新标签
     *
     * @param dto 更新DTO
     * @return 是否成功
     */
    Boolean updateTag(TagUpdateDTO dto);

    /**
     * 删除标签
     *
     * @param tagId 标签ID
     * @return 是否成功
     */
    Boolean deleteTag(Long tagId);

    /**
     * 获取标签详情
     *
     * @param tagId 标签ID
     * @return 标签VO
     */
    TagVO getTagDetail(Long tagId);

    /**
     * 分页查询标签
     *
     * @param dto 查询DTO
     * @return 分页结果
     */
    PageResult<TagVO> pageTags(TagQueryDTO dto);

    /**
     * 获取热门标签
     *
     * @param limit 数量限制
     * @return 标签列表
     */
    List<TagVO> getHotTags(Integer limit);

    /**
     * 根据分类获取标签
     *
     * @param categoryId 分类ID
     * @return 标签列表
     */
    List<TagVO> getTagsByCategory(Long categoryId);

    /**
     * 批量创建标签
     *
     * @param tagNames 标签名称列表
     * @return 标签ID列表
     */
    List<Long> batchCreateTags(List<String> tagNames);
}

6.2 创建Service实现类

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

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

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.knowledge.base.common.exception.BusinessException;
import com.knowledge.base.common.result.PageResult;
import com.knowledge.base.common.utils.SnowflakeIdGenerator;
import com.knowledge.base.document.dto.TagCreateDTO;
import com.knowledge.base.document.dto.TagQueryDTO;
import com.knowledge.base.document.dto.TagUpdateDTO;
import com.knowledge.base.document.entity.Tag;
import com.knowledge.base.document.mapper.TagMapper;
import com.knowledge.base.document.service.TagService;
import com.knowledge.base.document.vo.TagVO;
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 TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {

    @Resource
    private TagMapper tagMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createTag(TagCreateDTO dto) {
        log.info("创建标签:tagName={}", dto.getTagName());

        // 检查标签名称是否已存在
        Tag existTag = tagMapper.selectOne(
                new LambdaQueryWrapper<Tag>()
                        .eq(Tag::getTagName, dto.getTagName())
        );
        if (existTag != null) {
            throw new BusinessException("标签名称已存在");
        }

        // 生成标签编码
        String tagCode = StringUtils.hasText(dto.getTagName())
                ? generateTagCode(dto.getTagName())
                : "TAG_" + System.currentTimeMillis();

        // 构建标签实体
        Tag tag = new Tag();
        tag.setId(SnowflakeIdGenerator.getInstance().nextId());
        tag.setTagName(dto.getTagName());
        tag.setTagCode(tagCode);
        tag.setCategoryId(dto.getCategoryId());
        tag.setTagType(dto.getTagType() != null ? dto.getTagType() : 1);
        tag.setColor(dto.getColor());
        tag.setIcon(dto.getIcon());
        tag.setDocCount(0);
        tag.setStatus(1);

        // 保存标签
        int count = tagMapper.insert(tag);
        if (count <= 0) {
            throw new BusinessException("创建标签失败");
        }

        return tag.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTag(TagUpdateDTO dto) {
        log.info("更新标签:tagId={}", dto.getId());

        if (dto.getId() == null) {
            throw new BusinessException("标签ID不能为空");
        }

        // 检查标签是否存在
        Tag existTag = tagMapper.selectById(dto.getId());
        if (existTag == null) {
            throw new BusinessException("标签不存在");
        }

        // 检查标签名称是否被其他标签使用
        if (StringUtils.hasText(dto.getTagName())
                && !dto.getTagName().equals(existTag.getTagName())) {
            Tag tag = tagMapper.selectOne(
                    new LambdaQueryWrapper<Tag>()
                            .eq(Tag::getTagName, dto.getTagName())
            );
            if (tag != null && !tag.getId().equals(dto.getId())) {
                throw new BusinessException("标签名称已被使用");
            }
        }

        // 构建更新实体
        Tag tag = new Tag();
        tag.setId(dto.getId());
        if (StringUtils.hasText(dto.getTagName())) {
            tag.setTagName(dto.getTagName());
        }
        if (dto.getCategoryId() != null) {
            tag.setCategoryId(dto.getCategoryId());
        }
        if (dto.getColor() != null) {
            tag.setColor(dto.getColor());
        }
        if (dto.getIcon() != null) {
            tag.setIcon(dto.getIcon());
        }
        if (dto.getStatus() != null) {
            tag.setStatus(dto.getStatus());
        }

        int count = tagMapper.updateById(tag);
        return count > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteTag(Long tagId) {
        log.info("删除标签:tagId={}", tagId);

        if (tagId == null) {
            throw new BusinessException("标签ID不能为空");
        }

        // 检查标签是否存在
        Tag tag = tagMapper.selectById(tagId);
        if (tag == null) {
            throw new BusinessException("标签不存在");
        }

        // 检查是否有关联文档
        if (tag.getDocCount() != null && tag.getDocCount() > 0) {
            throw new BusinessException("该标签下有文档,不能删除");
        }

        // 删除标签
        int count = tagMapper.deleteById(tagId);
        return count > 0;
    }

    @Override
    public TagVO getTagDetail(Long tagId) {
        if (tagId == null) {
            throw new BusinessException("标签ID不能为空");
        }

        Tag tag = tagMapper.selectById(tagId);
        if (tag == null) {
            throw new BusinessException("标签不存在");
        }

        return convertToVO(tag);
    }

    @Override
    public PageResult<TagVO> pageTags(TagQueryDTO dto) {
        // 构建查询条件
        LambdaQueryWrapper<Tag> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(dto.getTagName())) {
            wrapper.like(Tag::getTagName, dto.getTagName())
                    .or()
                    .like(Tag::getTagCode, dto.getTagName());
        }
        if (dto.getCategoryId() != null) {
            wrapper.eq(Tag::getCategoryId, dto.getCategoryId());
        }
        if (dto.getTagType() != null) {
            wrapper.eq(Tag::getTagType, dto.getTagType());
        }
        wrapper.eq(Tag::getStatus, 1);

        // 分页查询
        Page<Tag> page = new Page<>(dto.getCurrent(), dto.getSize());
        IPage<Tag> tagPage = tagMapper.selectPage(page, wrapper);

        // 转换为VO
        IPage<TagVO> voPage = tagPage.convert(this::convertToVO);

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

    @Override
    public List<TagVO> getHotTags(Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 10;
        }

        List<Tag> tags = tagMapper.selectList(
                new LambdaQueryWrapper<Tag>()
                        .eq(Tag::getStatus, 1)
                        .orderByDesc(Tag::getDocCount)
                        .last("LIMIT " + limit)
        );

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

    @Override
    public List<TagVO> getTagsByCategory(Long categoryId) {
        if (categoryId == null) {
            throw new BusinessException("分类ID不能为空");
        }

        List<Tag> tags = tagMapper.selectList(
                new LambdaQueryWrapper<Tag>()
                        .eq(Tag::getCategoryId, categoryId)
                        .eq(Tag::getStatus, 1)
                        .orderByDesc(Tag::getDocCount)
        );

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Long> batchCreateTags(List<String> tagNames) {
        log.info("批量创建标签:tagCount={}", tagNames.size());

        if (tagNames == null || tagNames.isEmpty()) {
            return new ArrayList<>();
        }

        List<Long> tagIds = new ArrayList<>();

        for (String tagName : tagNames) {
            if (!StringUtils.hasText(tagName)) {
                continue;
            }

            // 检查标签是否已存在
            Tag existTag = tagMapper.selectOne(
                    new LambdaQueryWrapper<Tag>()
                            .eq(Tag::getTagName, tagName.trim())
            );

            Long tagId;
            if (existTag != null) {
                tagId = existTag.getId();
            } else {
                // 创建新标签
                TagCreateDTO dto = new TagCreateDTO();
                dto.setTagName(tagName.trim());
                dto.setTagType("USER");

                tagId = createTag(dto);
            }

            tagIds.add(tagId);
        }

        return tagIds;
    }

    /**
     * 转换为VO
     *
     * @param tag 标签实体
     * @return 标签VO
     */
    private TagVO convertToVO(Tag tag) {
        return TagVO.builder()
                .id(tag.getId())
                .tagName(tag.getTagName())
                .tagCode(tag.getTagCode())
                .categoryId(tag.getCategoryId())
                .tagType(tag.getTagType())
                .color(tag.getColor())
                .icon(tag.getIcon())
                .docCount(tag.getDocCount() != null ? tag.getDocCount() : 0)
                .status(tag.getStatus())
                .createdAt(tag.getCreateTime())
                .build();
    }

    /**
     * 生成标签编码
     *
     * @param tagName 标签名称
     * @return 标签编码
     */
    private String generateTagCode(String tagName) {
        // 简单的编码生成逻辑
        return "TAG_" + tagName.toUpperCase()
                .replaceAll("[^A-Z0-9]", "_")
                .replaceAll("_+", "_")
                .replaceAll("^_|_$", "") + "_" + System.currentTimeMillis();
    }
}

6.3 核心方法说明

6.3.1 批量创建标签

批量创建标签实现了"存在即用,不存在即创建"的逻辑:

@Override
@Transactional(rollbackFor = Exception.class)
public List<Long> batchCreateTags(List<String> tagNames) {
    List<Long> tagIds = new ArrayList<>();

    for (String tagName : tagNames) {
        // 检查标签是否已存在
        Tag existTag = tagMapper.selectOne(
            new LambdaQueryWrapper<Tag>()
                .eq(Tag::getTagName, tagName.trim())
        );

        if (existTag != null) {
            tagIds.add(existTag.getId());
        } else {
            // 创建新标签
            TagCreateDTO dto = new TagCreateDTO();
            dto.setTagName(tagName.trim());
            dto.setTagType(1); // 1-USER类型
            Long tagId = createTag(dto);
            tagIds.add(tagId);
        }
    }

    return tagIds;
}

这个方法在文档编辑时非常有用,用户输入标签后,系统自动创建不存在的标签。


七、控制器层

7.1 创建TagController

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

package com.knowledge.base.document.controller;

import com.knowledge.base.common.result.PageResult;
import com.knowledge.base.common.result.Result;
import com.knowledge.base.document.dto.TagCreateDTO;
import com.knowledge.base.document.dto.TagQueryDTO;
import com.knowledge.base.document.dto.TagUpdateDTO;
import com.knowledge.base.document.service.TagService;
import com.knowledge.base.document.vo.TagVO;
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("/api/tags")
@Tag(name = "标签管理", description = "标签管理相关接口")
public class TagController {

    @Resource
    private TagService tagService;

    /**
     * 创建标签
     */
    @PostMapping
    @Operation(summary = "创建标签", description = "创建新标签")
    public Result<Long> createTag(@Valid @RequestBody TagCreateDTO dto) {
        log.info("创建标签请求:tagName={}", dto.getTagName());

        Long tagId = tagService.createTag(dto);
        return Result.success("创建标签成功", tagId);
    }

    /**
     * 更新标签
     */
    @PutMapping
    @Operation(summary = "更新标签", description = "更新标签信息")
    public Result<Boolean> updateTag(@Valid @RequestBody TagUpdateDTO dto) {
        log.info("更新标签请求:tagId={}", dto.getId());

        Boolean result = tagService.updateTag(dto);
        return Result.success("更新标签成功", result);
    }

    /**
     * 删除标签
     */
    @DeleteMapping("/{tagId}")
    @Operation(summary = "删除标签", description = "删除指定标签")
    public Result<Boolean> deleteTag(
        @Parameter(description = "标签ID", required = true)
        @PathVariable Long tagId) {
        log.info("删除标签请求:tagId={}", tagId);

        Boolean result = tagService.deleteTag(tagId);
        return Result.success("删除标签成功", result);
    }

    /**
     * 获取标签详情
     */
    @GetMapping("/{tagId}")
    @Operation(summary = "获取标签详情", description = "根据ID获取标签详情")
    public Result<TagVO> getTagDetail(
        @Parameter(description = "标签ID", required = true)
        @PathVariable Long tagId) {
        log.info("获取标签详情请求:tagId={}", tagId);

        TagVO tagVO = tagService.getTagDetail(tagId);
        return Result.success(tagVO);
    }

    /**
     * 分页查询标签
     */
    @PostMapping("/page")
    @Operation(summary = "分页查询标签", description = "分页查询标签列表")
    public Result<PageResult<TagVO>> pageTags(@RequestBody TagQueryDTO dto) {
        log.info("分页查询标签请求:current={}, size={}", dto.getCurrent(), dto.getSize());

        PageResult<TagVO> pageResult = tagService.pageTags(dto);
        return Result.success(pageResult);
    }

    /**
     * 获取热门标签
     */
    @GetMapping("/hot")
    @Operation(summary = "获取热门标签", description = "获取使用最多的标签")
    public Result<List<TagVO>> getHotTags(
        @Parameter(description = "数量限制") @RequestParam(defaultValue = "10") Integer limit) {
        log.info("获取热门标签请求:limit={}", limit);

        List<TagVO> hotTags = tagService.getHotTags(limit);
        return Result.success(hotTags);
    }

    /**
     * 根据分类获取标签
     */
    @GetMapping("/category/{categoryId}")
    @Operation(summary = "根据分类获取标签", description = "获取指定分类下的标签")
    public Result<List<TagVO>> getTagsByCategory(
        @Parameter(description = "分类ID", required = true)
        @PathVariable Long categoryId) {
        log.info("根据分类获取标签请求:categoryId={}", categoryId);

        List<TagVO> tags = tagService.getTagsByCategory(categoryId);
        return Result.success(tags);
    }

    /**
     * 搜索标签
     */
    @GetMapping("/search")
    @Operation(summary = "搜索标签", description = "根据关键词搜索标签")
    public Result<List<TagVO>> searchTags(
        @Parameter(description = "搜索关键词", required = true)
        @RequestParam String keyword) {
        log.info("搜索标签请求:keyword={}", keyword);

        TagQueryDTO dto = new TagQueryDTO();
        dto.setTagName(keyword);
        dto.setCurrent(1L);
        dto.setSize(20L);

        PageResult<TagVO> pageResult = tagService.pageTags(dto);
        return Result.success(pageResult.getRecords());
    }
}

7.2 RESTful API设计

方法路径说明参数
POST/api/tags创建标签TagCreateDTO
PUT/api/tags更新标签TagUpdateDTO
DELETE/api/tags/{id}删除标签tagId
GET/api/tags/{id}查询标签tagId
POST/api/tags/page分页查询标签TagQueryDTO
GET/api/tags/hot获取热门标签limit
GET/api/tags/category/{id}按分类获取标签categoryId
GET/api/tags/search搜索标签keyword

八、测试验证

8.1 初始化测试数据

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

-- 插入系统标签 (tag_type = 0)
INSERT INTO tb_tag (id, tag_name, tag_code, category_id, tag_type, color, icon, doc_count, status) VALUES
(1000000000000000001, '置顶', 'TAG_TOP', NULL, 0, '#ff4d4f', '⭐', 0, 1),
(1000000000000000002, '推荐', 'TAG_RECOMMEND', NULL, 0, '#ffec3d', '🔥', 0, 1),
(1000000000000000003, '精选', 'TAG_FEATURED', NULL, 0, '#ffd666', '✨', 0, 1),
(1000000000000000004, '原创', 'TAG_ORIGINAL', NULL, 0, '#95de64', '📝', 5, 1),
(1000000000000000005, '翻译', 'TAG_TRANSLATE', NULL, 0, '#b37feb', '🌐', 2, 1);

-- 插入用户标签 (tag_type = 1)
INSERT INTO tb_tag (id, tag_name, tag_code, category_id, tag_type, color, icon, doc_count, status) VALUES
(1000000000000000006, 'Java', 'TAG_JAVA', 1000000000000000004, 1, '#f759ab', '☕', 10, 1),
(1000000000000000007, 'Spring Boot', 'TAG_SPRING_BOOT', 1000000000000000004, 1, '#6dd400', '🍃', 8, 1),
(1000000000000000008, 'Vue.js', 'TAG_VUE', 1000000000000000005, 1, '#42b883', '💚', 6, 1),
(1000000000000000009, 'React', 'TAG_REACT', 1000000000000000005, 1, '#61dafb', '⚛️', 5, 1),
(1000000000000000010, 'Python', 'TAG_PYTHON', 1000000000000000004, 1, '#ffd43b', '🐍', 7, 1);

8.2 测试标签CRUD

创建标签

curl -X POST http://localhost:8082/api/document/api/tags \
  -H "Content-Type: application/json" \
  -d '{
    "tagName": "MyBatis",
    "categoryId": 1000000000000000004,
    "tagType": 1,
    "color": "#e14329",
    "icon": "🍂"
  }'

更新标签

curl -X PUT http://localhost:8082/api/document/api/tags \
  -H "Content-Type: application/json" \
  -d '{
    "id": 1000000000000000006,
    "color": "#1890ff"
  }'

查询标签详情

curl http://localhost:8082/api/document/api/tags/1000000000000000006

分页查询标签

curl -X POST http://localhost:8082/api/document/api/tags/page \
  -H "Content-Type: application/json" \
  -d '{
    "current": 1,
    "size": 10,
    "tagType": 1
  }'

获取热门标签

curl "http://localhost:8082/api/document/api/tags/hot?limit=5"

根据分类获取标签

curl "http://localhost:8082/api/document/api/tags/category/1000000000000000004"

搜索标签

curl "http://localhost:8082/api/document/api/tags/search?keyword=Java"

删除标签

curl -X DELETE "http://localhost:8082/api/document/api/tags/1000000000000000010"

8.3 验证数据结构

热门标签接口返回示例:

{
  "code": 200,
  "message": "操作成功",
  "data": [
    {
      "id": 1000000000000000006,
      "tagName": "Java",
      "tagCode": "TAG_JAVA",
      "categoryId": 1000000000000000004,
      "tagType": 1,
      "color": "#f759ab",
      "icon": "☕",
      "docCount": 10,
      "status": 1,
      "createdAt": "2026-05-13T10:30:00"
    },
    {
      "id": 1000000000000000007,
      "tagName": "Spring Boot",
      "tagCode": "TAG_SPRING_BOOT",
      "categoryId": 1000000000000000004,
      "tagType": 1,
      "color": "#6dd400",
      "icon": "🍃",
      "docCount": 8,
      "status": 1,
      "createdAt": "2026-05-13T10:30:00"
    }
  ]
}

九、与文档模块集成

9.1 文档添加标签

在DocumentService中添加标签关联:

/**
 * 为文档添加标签
 */
@Transactional(rollbackFor = Exception.class)
public Boolean addTagsToDocument(Long documentId, List<Long> tagIds) {
    // 1. 验证文档存在
    Document document = documentMapper.selectById(documentId);
    if (document == null) {
        throw new BusinessException("文档不存在");
    }

    // 2. 删除旧的标签关联
    documentTagMapper.delete(
        new LambdaQueryWrapper<DocumentTag>()
            .eq(DocumentTag::getDocumentId, documentId)
    );

    // 3. 创建新的标签关联
    for (Long tagId : tagIds) {
        DocumentTag documentTag = new DocumentTag();
        documentTag.setId(SnowflakeIdGenerator.getInstance().nextId());
        documentTag.setDocumentId(documentId);
        documentTag.setTagId(tagId);
        documentTag.setCreateTime(LocalDateTime.now());
        documentTagMapper.insert(documentTag);

        // 增加标签的文档计数
        tagMapper.incrementDocumentCount(tagId);
    }

    // 4. 更新文档的标签字段(冗余)
    TagExample tagExample = new TagExample();
    tagExample.createCriteria().andIdIn(tagIds);
    List<Tag> tags = tagMapper.selectByExample(tagExample);
    String tagNames = tags.stream()
        .map(Tag::getTagName)
        .collect(Collectors.joining(","));

    Document updateDoc = new Document();
    updateDoc.setId(documentId);
    updateDoc.setTags(tagNames);
    documentMapper.updateById(updateDoc);

    return true;
}

9.2 删除文档时更新标签计数

/**
 * 删除文档前处理标签
 */
@PreRemove
public void beforeRemove(Document document) {
    // 获取文档的所有标签
    List<Long> tagIds = documentTagMapper.selectList(
        new LambdaQueryWrapper<DocumentTag>()
            .eq(DocumentTag::getDocumentId, document.getId())
    ).stream()
        .map(DocumentTag::getTagId)
        .collect(Collectors.toList());

    // 删除标签关联
    documentTagMapper.delete(
        new LambdaQueryWrapper<DocumentTag>()
            .eq(DocumentTag::getDocumentId, document.getId())
    );

    // 减少标签的文档计数
    for (Long tagId : tagIds) {
        tagMapper.decrementDocumentCount(tagId);
    }
}

总结

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

已完成功能

功能实现方式说明
标签CRUDService + Controller完整的增删改查
热门标签按docCount排序使用频率统计
分类关联按categoryId筛选标签分类管理
最后修改:2026 年 10 月 24 日
如果觉得我的文章对你有用,请随意赞赏