【京淘电商】04--商品分类模块

一,显示商品分类

1.业务接口文档

  • 请求路径: /itemCat/findItemCatList/{level}
  • 请求类型: get
  • 请求参数: level
参数名称参数说明备注
level查询级别1查询一级分类 2查询1-2 级商品分类 3查询1-2-3级商品分类
  • 业务说明: 查询3级分类菜单数据 要求三层结构嵌套
  • 返回值: SysResult对象
参数名称参数说明备注
status状态信息200表示服务器请求成功 201表示服务器异常
msg服务器返回的提示信息可以为null
data服务器返回的业务数据3级商品分类信息

2.编辑ItemCatController

	/**
     * 业务说明: 实现商品分类查询
     * URL:  /itemCat/findItemCatList/{level}
     * 参数:  level 查询的层级
     * 返回值: SysResult(List)
     */
    @GetMapping("/findItemCatList/{level}")
    public SysResult findItemCatList(@PathVariable Integer level){
        List<ItemCat> itemCatList = itemCatService.findItemCatList(level);
        return SysResult.success(itemCatList);
    }

3.编辑ItemCatService

@Override
    @Transactional
    public List<ItemCat> findItemCatList(Integer level) {
        long startTime = System.currentTimeMillis();
        QueryWrapper<ItemCat> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("level",level)
                .orderByDesc("level"); //根据level倒序查询出数据
        List<ItemCat> itemCatList = itemCatMapper.selectList(queryWrapper);
        int s = itemCatList.size();
        int a = 0;
        int b = 0;
        ItemCat itemCat;
        ItemCat itemCat1;
        for (int i = 0; i < s; i++) {
            itemCat = itemCatList.get(i);
            if (itemCat.getLevel() > 1 ) {          //如果获取的数据的level>1就停止循环
                for (int j = i + 1; j < s; j++) {
                    itemCat1 = itemCatList.get(j);
                    a = itemCat.getParentId();
                    b = itemCat1.getId();
                    if (a == b) {  //如果前面数据的parent_id与后面数据的id值相等,则将前面数据作为后面子对象
                        List<ItemCat> itemCatList1 = new ArrayList<>();
                        if (itemCat1.getChildren() != null) {
                            itemCatList1 = itemCat1.getChildren();
                        }
                        itemCatList1.add(itemCat);
                        itemCat1.setChildren(itemCatList1);
                    }
                }
            }
        }
        List<ItemCat> itemCatList2 = new ArrayList<>();
        for (ItemCat itemCat2 : itemCatList) {
            if (itemCat2.getLevel() == 1) {
                itemCatList2.add(itemCat2);
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("耗时:"+(endTime-startTime));
        return itemCatList2;
    }

嵌套逻辑分析点这里!!!

4.实现效果

在这里插入图片描述

二,商品分类状态修改

1.业务分析

当用户点击状态码时,应该实现数据的修改操作.
在这里插入图片描述

2.页面js分析

		<el-table-column prop="status" label="状态">
          <!-- 定义作用域插槽 展现数据     scope.row展现行级元素 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" active-color="#13ce66" inactive-color="#ff4949"
              @change="updateStatus(scope.row)"></el-switch>
          </template>
        </el-table-column>


	 //根据ID修改状态信息
      async updateStatus(itemCat) {
        const {
          data: result
        } = await this.$http.put(`/itemCat/status/${itemCat.id}/${itemCat.status}`)
        if (result.status !== 200) return this.$message.error("修改状态失败")
        this.$message.success("状态修改成功")
      },

3.业务接口实现

  • 请求路径: /itemCat/status/{id}/{status}
  • 请求类型: put
  • 请求参数:
参数名称参数说明备注
id用户ID值不能为null
status用户的状态信息不能为null
  • 返回值: SysResult对象
参数名称参数说明备注
status状态信息200表示服务器请求成功 201表示服务器异常
msg服务器返回的提示信息可以为null
data服务器返回的业务数据可以为null

4.编辑ItemCatController

	/**
     * 业务需求: ItemCat状态修改
     * URL地址: /itemCat/status/{id}/{status}
     * 参数:    id/status
     * 返回值:  SysResult对象
     */
    @PutMapping("/status/{id}/{status}")
    public SysResult updateStatus(ItemCat itemCat){

        itemCatService.updateStatus(itemCat);
        return SysResult.success();
    }

5.编辑ItemCatService

	@Override
    @Transactional //事务控制
    public void updateStatus(ItemCat itemCat) {

        itemCatMapper.updateById(itemCat);
    }

三,新增

1.业务说明

商品分类实现中,需要添加一级/二级/三级分类信息. 但是父级下拉框中勾选1-2级菜单. 因为三级菜单不能当作父级. 当用户编辑完成之后,点击确定实现商品分类入库.
在这里插入图片描述

2.页面js分析

	<!-- 2.1定义一行 使用栅格-->
      <el-row>
        <el-col :span="24">
          <el-button type="primary" @click="showAddItemCatDialog">新增分类</el-button>
        </el-col>
      </el-row>

 //当展现新增商品分类时,应该渲染级联框数据
      showAddItemCatDialog() {
        this.findParentItemCatList()
        this.addItemCatDialogVisible = true
      },
      async findParentItemCatList() {
        //动态获取商品分类信息  type=2表示获取2级商品分类信息
        const {
          data: result
        } = await this.$http.get("/itemCat/findItemCatList/2")
        if (result.status !== 200) return this.$message.error("获取商品分类列表失败!!")
        this.parentItemCatList = result.data
      },

	  //商品分类确定按钮实现
	   <span slot="footer" class="dialog-footer">
        <el-button @click="addItemCatDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addItemCatForm">确 定</el-button>
      </span>
	
	  //新增商品分类JS
	   async addItemCatForm() {
        //先将整个表单进行校验
        this.$refs.itemCatFormRef.validate(async validate => {
          if (!validate) return
          const {
            data: result
          } = await this.$http.post("/itemCat/saveItemCat", this.itemCatForm)
          if (result.status !== 200) return this.$message.error("新增商品分类失败")
          this.$message.success("新增商品分类成功!!!")
          //新增成功,则刷新分类列表信息
          this.findItemCatList();
          this.addItemCatDialogVisible = false
        })
      },

3.业务接口文档

  • 请求路径: /itemCat/saveItemCat
  • 请求类型: post
  • 请求参数: 表单数据
参数名称参数说明备注
name商品分类名称不能为null
parentId用户父级ID不能为null
level分类级别1 2 3 商品分类级别
  • 返回值: SysResult对象
参数名称参数说明备注
status状态信息200表示服务器请求成功 201表示服务器异常
msg服务器返回的提示信息可以为null
data服务器返回的业务数据可以为null

4.编辑ItemCatController

	/**
     * 业务分析: 完成商品分类新增
     * 请求类型: POST请求
     * URL: /itemCat/saveItemCat
     * 参数: 利用ItemCat对象接收 JSON
     * 返回值: SysResult对象
     */
    @PostMapping("/saveItemCat")
    public SysResult saveItemCat(@RequestBody ItemCat itemCat){

        itemCatService.saveItemCat(itemCat);
        return SysResult.success();
    }

5.编辑ItemCatService

@Override
    @Transactional
    public void saveItemCat(ItemCat itemCat) {
        itemCat.setStatus(true) ;
        itemCatMapper.insert(itemCat);
    }

四,修改操作

1.修改按钮JS分析

	<el-table-column label="操作">
          <!-- 定义作用域插槽 定义标签等级-->
          <template slot-scope="scope">
            <el-button type="success" icon="el-icon-edit" @click="updateItemCatBtn(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleteItemCatBtn(scope.row)">删除</el-button>
          </template>
        </el-table-column>


	 //由于有层级关系,所有修改只能修改名称
      updateItemCatBtn(itemCat) {
        this.updateItemCatForm = itemCat
        this.updateItemCatDialogVisible = true
      },

2.修改-确定按钮实现

	<!-- 添加修改分类对话框 -->
    <el-dialog title="修改商品分类" :visible.sync="updateItemCatDialogVisible" width="50%">
      <!-- 定义分类表单 -->
      <el-form :model="updateItemCatForm" :rules="rules" ref="upDateItemCatForm" label-width="100px">
        <el-form-item label="分类名称:" prop="name">
          <el-input v-model="updateItemCatForm.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateItemCatDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateItemCat">确 定</el-button>
      </span>
    </el-dialog>

	async updateItemCat() {
        //修改商品分类信息
        const {
          data: result
        } = await this.$http.put('/itemCat/updateItemCat', this.updateItemCatForm)
        if (result.status !== 200) return this.$message.error("更新商品分类失败")
        this.$message.success("更新商品分类成功")
        this.findItemCatList();
        this.updateItemCatDialogVisible = false;
      },	

3.业务接口文档

  • 请求路径: /itemCat/updateItemCat
  • 请求类型: put
  • 请求参数: 表单数据 ItemCat对象
  • 返回值: SysResult对象
参数名称参数说明备注
status状态信息200表示服务器请求成功 201表示服务器异常
msg服务器返回的提示信息可以为null
data服务器返回的业务数据可以为null

4.编辑ItemCatController

	/**
     * 需求: 实现商品分类修改操作
     * URL: /itemCat/updateItemCat
     * 参数: form表单  json  对象接收
     * 返回值: SysResult对象
     */
    @PutMapping("/updateItemCat")
    public SysResult updateItemCat(@RequestBody ItemCat itemCat){

        itemCatService.updateItemCat(itemCat);
        return SysResult.success();
    }

5.编辑ItemCatService

	@Override
    @Transactional
    public void updateItemCat(ItemCat itemCat) {

        itemCatMapper.updateById(itemCat);
    }

五,删除操作

1.业务说明

规则:
1.如果删除的商品分类是三级,则可以直接删除.
2.如果删除的商品分类是二级,则先删除三级,在删除二级.
3.如果删除的商品分类是一级,则先删除三级/二级/一级
注意事务的控制.

2.页面JS分析

	deleteItemCatBtn(itemCat) {
        //删除商品分类信息,如果为父级节点则需要删除所有的子级信息
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () =>{
          //传递分类id
          const {data: result} = await this.$http.delete("/itemCat/deleteItemCat",{params:{id:itemCat.id,level:itemCat.level}})
          if(result.status !== 200) return this.$message.error("删除商品分类失败")
          this.$message.success("删除数据成功")
          //删除成功之后,刷新页面数据
          this.findItemCatList()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除AAAAAAA'
          });
        });
      }

3.业务接口实现

  • 请求路径: /itemCat/deleteItemCat
  • 请求类型: delete
  • 业务描述: 当删除节点为父级时,应该删除自身和所有的子节点
  • 请求参数:
参数名称参数说明备注
id用户id号不能为null
level商品分类级别 一级,二级,三级
  • 返回值结果 SysResult对象
参数名称参数说明备注
status状态信息200表示服务器请求成功 201表示服务器异常
msg服务器返回的提示信息可以为null
data服务器返回的业务数据可以为null

4.编辑ItemCatController

	/**
     * 业务需求: 实现商品分类删除
     * URL: /itemCat/deleteItemCat?id=xx&level=2
     * 参数: id/level
     * 返回值: SysResult对象
     */
    @DeleteMapping("/deleteItemCat")
    public SysResult deleteItemCats(ItemCat itemCat){

        itemCatService.deleteItemCats(itemCat);
        return SysResult.success();
    }

5.编辑ItemCatService

//删除数据
    @Override
    @Transactional
    public void deleteItemCat(ItemCat itemCat) {
        long start = System.currentTimeMillis();
        int level = itemCat.getLevel();
        itemCatMapper.deleteById(itemCat.getId());
        List<Integer> ids = new ArrayList<>(); //存放子分类的id
        ids.add(itemCat.getId());
        while (level < 3) {
            ids = itemCatMapper.selectIdsByPIDs(ids);
            System.out.println(ids);
            if (ids.isEmpty()) {
                break;
            }
            itemCatMapper.deleteBatchIds(ids);
            level++;

        }
        long end = System.currentTimeMillis();
        System.out.println("耗时:" + (end - start));
    }

六,完整代码

页面

<template>
  <div>
    <!-- 1.定义面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 2.定义卡片视图 -->
    <el-card class="box-card">

      <!-- 2.1定义一行 使用栅格-->
      <el-row>
        <el-col :span="24">
          <el-button type="primary" @click="showAddItemCatDialog">新增分类</el-button>
        </el-col>
      </el-row>

      <!-- 2.2定义表格数据-->
      <el-table :data="itemCatList" style="width: 100%;margin-bottom: 20px;" row-key="id" border stripe>
        <el-table-column type="index" label="序号">
        </el-table-column>
        <el-table-column prop="name" label="分类名称">
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <!-- 定义作用域插槽 展现数据     scope.row展现行级元素 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" active-color="#13ce66" inactive-color="#ff4949"
              @change="updateStatus(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="等级">
          <!-- 定义作用域插槽 定义标签等级-->
           <template slot-scope="scope">
            <el-tag effect="dark" v-if="scope.row.level == 1">一级分类</el-tag>
            <el-tag effect="dark" type="warning" v-if="scope.row.level == 2">二级分类</el-tag>
            <el-tag effect="dark" type="danger" v-if="scope.row.level == 3">三级分类</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- 定义作用域插槽 定义标签等级-->
          <template slot-scope="scope">
            <el-button type="success" icon="el-icon-edit" @click="updateItemCatBtn(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleteItemCatBtn(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-card>

    <!-- 添加新增分类对话框-->
    <el-dialog title="新增商品分类" :visible.sync="addItemCatDialogVisible" width="50%" @close="closeAddItemCatDialog">
      <!-- 定义分类表单 -->
      <el-form :model="itemCatForm" :rules="rules" ref="itemCatFormRef" label-width="100px">
        <el-form-item label="分类名称:" prop="name">
          <el-input v-model="itemCatForm.name"></el-input>
        </el-form-item>
        <!-- 定义父级分类选项 -->
        <el-form-item label="父级分类名称:">
          <!-- 通过级联选择器定义1/2级商品分类
             步骤:  1.注意标签导入
                    2.options 表示数据的来源
                    3.指定props属性指定数据配置
          -->
          <el-cascader v-model="selectedKeys" :props="props" :options="parentItemCatList" clearable
            @change="parentItemCatChange"></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addItemCatDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addItemCatForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加修改分类对话框 -->
    <el-dialog title="修改商品分类" :visible.sync="updateItemCatDialogVisible" width="50%">
      <!-- 定义分类表单 -->
      <el-form :model="updateItemCatForm" :rules="rules" ref="upDateItemCatForm" label-width="100px">
        <el-form-item label="分类名称:" prop="name">
          <el-input v-model="updateItemCatForm.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateItemCatDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateItemCat">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    //定义初始化函数
    created() {
      //默认获取商品分类列表数据
      this.findItemCatList()
    },
    data() {
      return {
        //定义商品分类数据
        itemCatList: [],
        //控制分类对话框的显示
        addItemCatDialogVisible: false,
        //定义商品分类新增对象
        itemCatForm: {
          name: '', //定义商品分类名称
          parentId: 0, //默认父级ID=0
          level: 1 //默认是一级菜单
        },
        //定义商品分类校验规则
        rules: {
          name: [{
            required: true,
            message: '请输入分类名称',
            trigger: 'blur'
          }]
        },

        //定义级联选择项
        props: {
          //定义子节点菜单展开方式
          expandTrigger: "hover",
          value: "id", //选中数据的value值
          label: "name", //选中数据展现名称
          children: "children", //自选项数据
          checkStrictly: true
        },
        //定义用户选中父级ID数组
        selectedKeys: [],
        //定义父级商品分类信息只查询一级和二级
        parentItemCatList: [],
        //定义修改对话框属性
        updateItemCatDialogVisible: false,
        updateItemCatForm: {}
      }
    },
    methods: {
      async findItemCatList() {
        const {
          data: result
        } = await this.$http.get("/itemCat/findItemCatList/3")
        if (result.status !== 200) return this.$message.error("获取商品分类列表失败!!")
        this.itemCatList = result.data
      },
      //根据ID修改状态信息
      async updateStatus(itemCat) {
        const {
          data: result
        } = await this.$http.put(`/itemCat/status/${itemCat.id}/${itemCat.status}`)
        if (result.status !== 200) return this.$message.error("修改状态失败")
        this.$message.success("状态修改成功")
      },
      //当展现新增商品分类时,应该渲染级联框数据
      showAddItemCatDialog() {
        this.findParentItemCatList()
        this.addItemCatDialogVisible = true
      },
      async findParentItemCatList() {
        //动态获取商品分类信息  type=2表示获取2级商品分类信息
        const {
          data: result
        } = await this.$http.get("/itemCat/findItemCatList/2")
        if (result.status !== 200) return this.$message.error("获取商品分类列表失败!!")
        this.parentItemCatList = result.data
      },
      //当选择项发生变化时,触发该函数
      parentItemCatChange() {
        console.log(this.selectedKeys)
        console.log(this.itemCatForm)
        //如果选中节点的长度>0 则表示不是一级商品分类
        if (this.selectedKeys.length > 0) {
          //[1,2] 主要获取最后一位
          this.itemCatForm.parentId = this.selectedKeys[this.selectedKeys.length - 1]
          //数组级别+1
          this.itemCatForm.level = this.selectedKeys.length + 1
        } else {
          //如果数组长度不大于0 则表示一级商品分类信息
          this.itemCatForm.parentId = 0
          this.itemCatForm.level = 1
        }
      },
      async addItemCatForm() {
        //先将整个表单进行校验
        this.$refs.itemCatFormRef.validate(async validate => {
          if (!validate) return
          const {
            data: result
          } = await this.$http.post("/itemCat/saveItemCat", this.itemCatForm)
          if (result.status !== 200) return this.$message.error("新增商品分类失败")
          this.$message.success("新增商品分类成功!!!")
          //新增成功,则刷新分类列表信息
          this.findItemCatList();
          this.addItemCatDialogVisible = false
        })
      },
      //当点击关闭按钮时,应该重置整个表单
      closeAddItemCatDialog() {
        this.initItemCatForm()
      },
      initItemCatForm() {
        this.$refs.itemCatFormRef.resetFields()
        //清空form提交其他数据
        this.itemCatForm.parentId = 0
        this.itemCatForm.level = 1
        //清空级联选择框的数组
        this.selectedKeys = []
      },
      //由于有层级关系,所有修改只能修改名称
      updateItemCatBtn(itemCat) {
        this.updateItemCatForm = itemCat
        this.updateItemCatDialogVisible = true
      },
      async updateItemCat() {
        //修改商品分类信息
        const {
          data: result
        } = await this.$http.put('/itemCat/updateItemCat', this.updateItemCatForm)
        if (result.status !== 200) return this.$message.error("更新商品分类失败")
        this.$message.success("更新商品分类成功")
        this.findItemCatList();
        this.updateItemCatDialogVisible = false;
      },
      deleteItemCatBtn(itemCat) {
        //删除商品分类信息,如果为父级节点则需要删除所有的子级信息
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () =>{
          //传递分类id
          const {data: result} = await this.$http.delete("/itemCat/deleteItemCat",{params:{id:itemCat.id,level:itemCat.level}})
          if(result.status !== 200) return this.$message.error("删除商品分类失败")
          this.$message.success("删除数据成功")
          //删除成功之后,刷新页面数据
          this.findItemCatList()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    }
  }
</script>

<style lang="less" scoped>
  /*定义级联选择器宽度 */
  .el-cascader {
    width: 100%;
  }
</style>

业务层

@Service
public class ItemCatServiceImpl implements ItemCatService{
    @Autowired
    private ItemCatMapper itemCatMapper;

    @Override
    public List<ItemCat> findAll() {
        long startTime = System.currentTimeMillis();
        QueryWrapper<ItemCat> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("level"); //根据level倒序查询出数据
        List<ItemCat> itemCatList = itemCatMapper.selectList(queryWrapper);
        int s = itemCatList.size();
        for (int i = 0; i < s; i++) {
            ItemCat itemCat = itemCatList.get(i);
            if (itemCat.getLevel() > 1 ) {          //如果获取的数据的level>1就停止循环
                for (int j = i + 1; j < s; j++) {
                    ItemCat itemCat1 = itemCatList.get(j);
                    if (itemCat1.getId().equals(itemCat.getParentId())) {  //如果前面数据的parent_id与后面数据的id值相等,则将前面数据作为后面子对象
                        List<ItemCat> itemCatList1 = new ArrayList<>();
                        if (itemCat1.getChildren() != null) {
                            itemCatList1 = itemCat1.getChildren();
                        }
                        itemCatList1.add(itemCat);
                        itemCat1.setChildren(itemCatList1);
                    }
                }
            }
        }
        List<ItemCat> itemCatList2 = new ArrayList<>();
        for (int i = 0; i < itemCatList.size(); i++) { //只获取level为1的数据
            ItemCat itemCat = itemCatList.get(i);
            if (itemCat.getLevel() == 1) {
                itemCatList2.add(itemCat);
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("耗时:"+(endTime - startTime));
        return itemCatList2;
    }

    @Override
    @Transactional
    public List<ItemCat> findItemCatList(Integer level) {
        long startTime = System.currentTimeMillis();
//        QueryWrapper<ItemCat> queryWrapper = new QueryWrapper<>();
//        queryWrapper.orderByDesc("level")
//                    .le("level",level);
//        int a = 0;
//        int b = 0;
//        List<ItemCat> itemCatList = itemCatMapper.selectList(queryWrapper);
//        for (ItemCat itemCat : itemCatList) {
//            if (itemCat.getLevel() > 1 ) {
//                for (ItemCat itemCat1 : itemCatList) {
//                    a = itemCat.getParentId();
//                    b = itemCat.getId();
//                    if (a == b) {
//                        List<ItemCat> itemCatList1 = new ArrayList<>();
//                        if (itemCat1.getChildren() != null) {
//                            itemCatList1 = itemCat1.getChildren();
//                        }
//                        itemCatList1.add(itemCat);
//                        itemCat1.setChildren(itemCatList1);
//                        break;
//                    }
//                }
//            }
//        }
        QueryWrapper<ItemCat> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("level",level)
                .orderByDesc("level"); //根据level倒序查询出数据
        List<ItemCat> itemCatList = itemCatMapper.selectList(queryWrapper);
        int s = itemCatList.size();
        int a = 0;
        int b = 0;
        ItemCat itemCat;
        ItemCat itemCat1;
        for (int i = 0; i < s; i++) {
            itemCat = itemCatList.get(i);
            if (itemCat.getLevel() > 1 ) {          //如果获取的数据的level>1就停止循环
                for (int j = i + 1; j < s; j++) {
                    itemCat1 = itemCatList.get(j);
                    a = itemCat.getParentId();
                    b = itemCat1.getId();
                    if (a == b) {  //如果前面数据的parent_id与后面数据的id值相等,则将前面数据作为后面子对象
                        List<ItemCat> itemCatList1 = new ArrayList<>();
                        if (itemCat1.getChildren() != null) {
                            itemCatList1 = itemCat1.getChildren();
                        }
                        itemCatList1.add(itemCat);
                        itemCat1.setChildren(itemCatList1);
                    }
                }
            }
        }
        List<ItemCat> itemCatList2 = new ArrayList<>();
        for (ItemCat itemCat2 : itemCatList) {
            if (itemCat2.getLevel() == 1) {
                itemCatList2.add(itemCat2);
            }
        }
//        Map<Integer,List<ItemCat>> map = getMap();
//        if (level == 1) {
//            return map.get(0);
//        }
//        if (level == 2) {
//            return getTwoList(map);
//        }
//        List<ItemCat> itemCatList = getThreeList(map);
//        QueryWrapper<ItemCat> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("parent_id",0);
//        List<ItemCat> oneList = itemCatMapper.selectList(queryWrapper);
//        //2.遍历一级菜单 根据一级查询二级菜单
//        for (ItemCat oneItemCat : oneList){
//            queryWrapper.clear();
//            queryWrapper.eq("parent_id",oneItemCat.getId());
//            List<ItemCat> twoList = itemCatMapper.selectList(queryWrapper);
//
//            //3.将二级列表进行遍历,根据二级ID查询三级
//            for(ItemCat twoItemCat : twoList){
//                queryWrapper.clear();
//                queryWrapper.eq("parent_id",twoItemCat.getId());
//                List<ItemCat> threeList = itemCatMapper.selectList(queryWrapper);
//                //数据的封装
//                twoItemCat.setChildren(threeList);
//            }
//            //将二级数据封装到一级中
//            oneItemCat.setChildren(twoList);
//        }
        long endTime = System.currentTimeMillis();
        System.out.println("耗时:"+(endTime-startTime));
        //return itemCatList;
        return itemCatList2;
        //return oneList;
    }
    //根据ID修改分类状态
    @Override
    public void updateStatus(ItemCat itemCat) {
        itemCatMapper.updateById(itemCat);
    }
    //添加分类信息
    @Override
    public void saveItemCat(ItemCat itemCat) {
        itemCat.setStatus(true);
        itemCatMapper.insert(itemCat);
    }
    //修改数据
    @Override
    public void updateItemCat(ItemCat itemCat) {
        itemCatMapper.updateById(itemCat);
    }
    //删除数据
    @Override
    @Transactional
    public void deleteItemCat(ItemCat itemCat) {
        long start = System.currentTimeMillis();
        int level = itemCat.getLevel();
        itemCatMapper.deleteById(itemCat.getId());
        List<Integer> ids = new ArrayList<>(); //存放子分类的id
        ids.add(itemCat.getId());
        while (level < 3) {
            ids = itemCatMapper.selectIdsByPIDs(ids);
            System.out.println(ids);
            if (ids.isEmpty()) {
                break;
            }
            itemCatMapper.deleteBatchIds(ids);
            level++;

        }
//        List<ItemCat> itemCats = itemCatMapper.selectList(null);
//        List<Integer> deleteListIds = new ArrayList<>();
//        deleteListIds.add(itemCat.getId());
//        for (int i = 0; i < deleteListIds.size(); i++) {
//            for (ItemCat itemCat1 : itemCats) {
//                if (itemCat1.getParentId().equals(deleteListIds.get(i))) {
//                    deleteListIds.add(itemCat1.getId());
//                }
//            }
//        }
//        int i = itemCatMapper.deleteBatchIds(deleteListIds);
        long end = System.currentTimeMillis();
        System.out.println("耗时:" + (end - start));
    }
    private Map<Integer,List<ItemCat>> getMap() {
        Map<Integer,List<ItemCat>> map = new HashMap<>();
        List<ItemCat> list = itemCatMapper.selectList(null);
        for (ItemCat itemCat : list) {
            //获取parent_id
            int parentId = itemCat.getParentId();
            if (map.containsKey(parentId)) {
                //key 存在
                map.get(parentId).add(itemCat);
            } else {
                //key不存在
                List<ItemCat> children = new ArrayList<>();
                children.add(itemCat);
                map.put(parentId,children);
            }
        }
        return map;
    }
    private List<ItemCat> getTwoList(Map<Integer,List<ItemCat>> map) {
        //1.先获取一级列表
        List<ItemCat> oneList = map.get(0);
        //根据一级查询二级
        for (ItemCat oneItemCat : oneList) {
            //查询二级,所以parentId是一级的Id
            int parentId = oneItemCat.getId();
            List<ItemCat> twoList = map.get(parentId);
            //封装数据
            oneItemCat.setChildren(twoList);
        }
        return oneList;
    }
    private List<ItemCat> getThreeList(Map<Integer,List<ItemCat>> map) {
        //获取一级和二级
        List<ItemCat> oneList = getTwoList(map);
        //封装三级,遍历二级菜单,之后封装
        for (ItemCat oneItemCat : oneList) {
            //获取二级集合
            List<ItemCat> twoList = oneItemCat.getChildren();
            if (twoList == null || twoList.size() == 0) {
                //由于业务数据不合理,跳过本次循环,执行下一次
                continue;
            }
            for (ItemCat twoItemCat : twoList) {
                //查询三级列表,需要parentId = 二级ID
                int parentId = twoItemCat.getId();
                List<ItemCat> threeList = map.get(parentId);
                twoItemCat.setChildren(threeList);
            }
        }
        return oneList;
    }
}

控制层

@RestController
@RequestMapping("/itemCat")
@CrossOrigin
public class ItemCatController {
    @Autowired
    private ItemCatService itemCatService;
    @GetMapping("/findAll")
    public List<ItemCat> findAll() {
        return itemCatService.findAll();
    }
    /**
     * 业务说明: 实现商品分类查询
     * URL: /itemCat/findItemCatList/{level}
     * 参数: level 查询的层级
     * 返回值: SysResult(List)
     */
    @GetMapping("/findItemCatList/{level}")
    public SysResult findItemCatList(@PathVariable Integer level) {
        return SysResult.success(itemCatService.findItemCatList(level));
    }
    /**
     * 业务说明: 根据ID修改状态信息
     * URL地址: /itemCat/status/{id}/{status}
     * 参数: id/status
     * 返回值: SysResult对象
     */
    @PutMapping("/status/{id}/{status}")
    public SysResult updateStatus(ItemCat itemCat) {
        itemCatService.updateStatus(itemCat);
        return SysResult.success();
    }
    /**
     * 业务说明: 添加信息
     */
    @PostMapping("/saveItemCat")
    public SysResult saveItemCat(@RequestBody ItemCat itemCat) {
        itemCatService.saveItemCat(itemCat);
        return SysResult.success();
    }
    /**
     * 业务需求: 修改分类名称
     * URL: /itemCat/updateItemCat
     * 参数: form表单 json 对象接收
     * 返回值: SysResult对象
     */
    @PutMapping("/updateItemCat")
    public SysResult updateItemCat(@RequestBody ItemCat itemCat) {
        itemCatService.updateItemCat(itemCat);
        return SysResult.success();
    }
    /**
     * 业务需求: 删除数据
     */
    @DeleteMapping("/deleteItemCat")
    public SysResult deleteItemCat(ItemCat itemCat) {
        itemCatService.deleteItemCat(itemCat);
        return SysResult.success();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值