自学内容网 自学内容网

016 规格参数


分类属性属性分组

vo

新增

AttrController.java

@RestController
@RequestMapping("product/attr")
public class AttrController {
    @Autowired
    private AttrService attrService;

    /**
     * 保存
     */
    @RequestMapping("/save")
    //@RequiresPermissions("product:attr:save")
    public R save(@RequestBody AttrVo attrVo){
attrService.saveAttr(attrVo);

        return R.ok();
    }
   
}

AttrVo.java

package com.xd.cubemall.product.vo;



import lombok.Data;

@Data
public class AttrVo {
    private static final long serialVersionUID = 1L;

    /**
     * 自增ID
     */
    private Long id;
    /**
     * 名称
     */
    private String name;
    /**
     * 搜索类型
     */
    private Integer searchType;
    /**
     * 图标
     */
    private String icon;
    /**
     * 选择值
     */
    private String valueSelect;
    /**
     * 属性类型:0-销售属性,1-基本属性,2-既是基本属性又是销售属性
     */
    private Integer attrType;
    /**
     * 启用
     */
    private Long enable;
    /**
     * 分类ID
     */
    private Integer categoryId;
    /**
     * 描述
     */
    private Integer showDesc;

    /**
     * 分组ID
     */
    private Long attrGroupId;
}

AttrServiceImpl.java

@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    /**
     * 在attr表中保存基本属性信息,然后在关联表中保存关联信息
     * @param attrVo
     */
    @Override
    public void saveAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        //保存基本属性数据
        this.save(attrEntity);
        //在AttrServiceImpl类中,this.save(attrEntity)这一行代码中的this关键字指的是当前对象的实例,即AttrServiceImpl的一个实例。在这里,this代表了正在执行代码的AttrServiceImpl类的对象。
        //
        //save方法是ServiceImpl类中的一个方法,该类是AttrServiceImpl的父类(通过extends ServiceImpl<AttrDao, AttrEntity>)。ServiceImpl类是MyBatis-Plus框架中提供的一个基础服务实现类,它封装了一些常用的CRUD(创建、读取、更新、删除)操作。save方法用于保存或插入一个新的实体到数据库中。
        //
        //因此,当你调用this.save(attrEntity)时,你实际上是在调用从ServiceImpl类继承来的save方法,将attrEntity对象保存到数据库中。这个方法会利用MyBatis-Plus提供的ORM(对象关系映射)功能,将AttrEntity对象的属性与数据库表中的列进行映射,并执行插入操作。


        //保存关联数据
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelationEntity.setAttrId(attrEntity.getId());
        attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());

        attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        
    }
}

AttrAttrgroupRelationEntity.java

package com.xd.cubemall.product.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;
import java.util.Date;
import lombok.Data;

/**
 * 属性分组关联表
 * 
 * @author xuedong
 * @email email@gmail.com
 * @date 2024-08-13 01:36:04
 */
@Data
@TableName("tb_attr_attrgroup_relation")
public class AttrAttrgroupRelationEntity implements Serializable {
private static final long serialVersionUID = 1L;

/**
 * id
 */
@TableId
private Long id;
/**
 * 属性ID
 */
private Long attrId;
/**
 * 属性分组ID
 */
private Long attrGroupId;
/**
 * 排序
 */
private Integer attrSort;

}

AttrEntity.java

package com.xd.cubemall.product.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;
import java.util.Date;
import lombok.Data;

/**
 * 属性表
 * 
 * @author xuedong
 * @email email@gmail.com
 * @date 2024-08-13 01:36:04
 */
@Data
@TableName("tb_attr")
public class AttrEntity implements Serializable {
private static final long serialVersionUID = 1L;

/**
 * 自增ID
 */
@TableId
private Long id;
/**
 * 名称
 */
private String name;
/**
 * 搜索类型
 */
private Integer searchType;
/**
 * 图表
 */
private String icon;
/**
 * 选择值
 */
private String valueSelect;
/**
 * 属性类型:0-销售属性,1-基本属性,2-既是基本属性又是销售属性
 */
private Integer attrType;
/**
 * 启用
 */
private Long enable;
/**
 * 分类ID
 */
private Integer categoryId;
/**
 * 描述
 */
private Integer showDesc;

}

AttrGroupEntity.java

package com.xd.cubemall.product.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;
import java.util.Date;
import lombok.Data;

/**
 * 属性分组表
 * 
 * @author xuedong
 * @email email@gmail.com
 * @date 2024-08-13 01:36:04
 */
@Data
@TableName("tb_attr_group")
public class AttrGroupEntity implements Serializable {
private static final long serialVersionUID = 1L;

/**
 * 自增ID
 */
@TableId
private Long id;
/**
 * 名称
 */
private String name;
/**
 * 排序
 */
private Integer sort;
/**
 * 描述
 */
private String descript;
/**
 * 图表
 */
private String icon;
/**
 * 分类ID
 */
private Integer categoryId;

/**
 * 完整的categoryID的路径
 */
@TableField(exist = false)
private Long[] categoryPath;
}

查询

AttrController.java

@RestController
@RequestMapping("product/attr")
public class AttrController {
    @Autowired
    private AttrService attrService;

    /**
     * 列表
     */
    @RequestMapping("/base/list/{categoryId}")
    //@RequiresPermissions("product:attr:list")
    public R list(@RequestParam Map<String, Object> params,@PathVariable("categoryId") Long categoryId){
        PageUtils page = attrService.queryBaseAttrPage(params, categoryId);

        return R.ok().put("page", page);
    }

}

AttrServiceImpl.java

@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;


    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

/**  
 * 获取指定分类的所有基本属性列表  
 * @param params 查询参数,可能包含分页信息和其他筛选条件  
 * @param categoryId 分类ID,用于筛选属性所属的分类  
 * @return 封装了查询结果和分页信息的PageUtils对象  
 */  
@Override  
public PageUtils queryBaseAttrPage(Map<String, Object> params, Long categoryId) {  
    // 创建一个QueryWrapper对象,用于构建查询条件  
    QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();  
      
    // 如果categoryId不为0,则添加查询条件:属性所属的分类ID等于传入的categoryId  
    if (categoryId != 0) {  
        queryWrapper.eq("category_id", categoryId);  
    }  
      
    // 从查询参数中获取关键字key  
    String key = (String) params.get("key");  
    // 如果key不为空,则添加查询条件:属性ID等于key或者属性名称包含key  
    // 注意:这里的逻辑可能有些问题,因为通常我们不会用ID来做模糊查询,这里可能是为了演示多种查询方式  
    // 实际上,应该根据实际需求来调整查询逻辑  
    if (StringUtils.isEmpty(key)){ // 这里判断应该是 !StringUtils.isEmpty(key),即key不为空时才执行查询  
        queryWrapper.and(wrapper -> {  
            wrapper.eq("id", key).or().like("name", key);  
        });  
    }  
      
    // 使用分页查询,获取属性列表的分页结果  
    IPage<AttrEntity> page = this.page(  
            new Query<AttrEntity>().getPage(params), // 从查询参数中获取分页信息  
            queryWrapper // 传入构建好的查询条件  
    );  
  
    // 创建一个PageUtils对象,用于封装分页结果和额外信息  
    PageUtils pageUtils = new PageUtils(page);  
      
    // 获取分页结果中的属性列表  
    List<AttrEntity> records = page.getRecords();  
      
    // 使用Java 8的Stream API对属性列表进行转换,封装成包含额外信息的AttrRespVo对象列表  
    List<AttrRespVo> respVos = records.stream().map(attrEntity -> {  
        // 创建一个AttrRespVo对象,用于封装返回的属性信息  
        AttrRespVo attrRespVo = new AttrRespVo();  
          
        // 1. 复制属性实体的基础信息到AttrRespVo对象中  
        BeanUtils.copyProperties(attrEntity, attrRespVo);  
          
        // 2. 封装属性分组名称  
        // 根据属性ID查询属性与属性分组的关联关系  
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(  
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getId())  
        );  
        // 如果关联关系存在,则根据关联的属性分组ID查询属性分组名称  
        if (attrAttrgroupRelationEntity != null) {  
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());  
            if (attrGroupEntity != null) {  
                attrRespVo.setGroupName(attrGroupEntity.getName());  
            }  
        }  
          
        // 3. 封装分类名称  
        // 根据属性所属的分类ID查询分类名称  
        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCategoryId());  
        if (categoryEntity != null) {  
            attrRespVo.setCategoryName(categoryEntity.getName());  
        }  
          
        // 返回封装好的AttrRespVo对象  
        return attrRespVo;  
    }).collect(Collectors.toList());  
      
    // 将封装好的AttrRespVo对象列表设置到PageUtils对象中  
    pageUtils.setList(respVos);  
      
    // 返回封装了查询结果和分页信息的PageUtils对象  
    return pageUtils;  
}
}

AttrRespVo.java

package com.xd.cubemall.product.vo;

import lombok.Data;

@Data
public class AttrRespVo extends AttrVo{

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


    /**
     * 属性分组名称
     */
    private String groupName;


    /**
     * 分类路径
     */
    private Long[] categoryPath;
}

修改回显

AttrController.java

    /**
     * 指定属性信息的回显
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("product:attr:info")
    public R info(@PathVariable("id") Long id){
//AttrEntity attr = attrService.getById(id);
        AttrRespVo attrRespVo = attrService.getAttrInfo(id);


        return R.ok().put("attr", attrRespVo);
    }

AttrServiceImpl.java

import com.xd.cubemall.common.utils.PageUtils;
import com.xd.cubemall.common.utils.Query;
import com.xd.cubemall.product.dao.AttrAttrgroupRelationDao;
import com.xd.cubemall.product.dao.AttrGroupDao;
import com.xd.cubemall.product.dao.CategoryDao;
import com.xd.cubemall.product.entity.AttrAttrgroupRelationEntity;
import com.xd.cubemall.product.entity.AttrGroupEntity;
import com.xd.cubemall.product.entity.CategoryEntity;
import com.xd.cubemall.product.service.CategoryService;
import com.xd.cubemall.product.vo.AttrRespVo;
import com.xd.cubemall.product.vo.AttrVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.xd.cubemall.product.dao.AttrDao;
import com.xd.cubemall.product.entity.AttrEntity;
import com.xd.cubemall.product.service.AttrService;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;


    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public AttrRespVo getAttrInfo(Long id) {

        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(id);
        //attrEntity中的基本属性 拷贝到 attrRespVo
        BeanUtils.copyProperties(attrEntity,attrRespVo);
        //1.设置分组信息
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getId())
        );
        if (attrAttrgroupRelationEntity != null) {
            attrRespVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
            if (attrGroupEntity != null) {
                attrRespVo.setGroupName(attrGroupEntity.getName());
            }
        }

        //2.设置分类路径
        Long[] categoryPath = categoryService.findCategoryPath(attrEntity.getCategoryId());
        attrRespVo.setCategoryPath(categoryPath);

        //3.设置分类名称
        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCategoryId());
        if (categoryEntity != null) {
            attrRespVo.setCategoryName(categoryEntity.getName());
        }
        return attrRespVo;
    }

}

修改提交

AttrController.java

    /**
     * 修改提交操作
     */
    @RequestMapping("/update")
    //@RequiresPermissions("product:attr:update")
    public R update(@RequestBody AttrVo attrVo){
attrService.updateAttr(attrVo);

        return R.ok();
    }

AttrServiceImpl.java

    /**
     * 基本属性的修改--提交操作
     * @param attrVo
     */
    @Override
    public void updateAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        //基本属性的对拷
        BeanUtils.copyProperties(attrVo,attrEntity);
        this.updateById(attrEntity);

        //修改属性分组关联
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelationEntity.setAttrId(attrVo.getId());
        attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());

        Integer count = attrAttrgroupRelationDao.selectCount(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getId())
        );
        if(count > 0){
            attrAttrgroupRelationDao.update(
              attrAttrgroupRelationEntity,
              new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrVo.getId())
            );
        }else {
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);

        }
    }

baseattr.vue

<template>
  <el-row :gutter="20">
    <el-col :span="6">
      <category @tree-node-click="treenodeclick"></category>
    </el-col>
    <el-col :span="18">
      <div class="mod-config">
        <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
          <el-form-item>
            <el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="getDataList()">查询</el-button>
            <el-button type="success" @click="getAllDataList()">查询全部</el-button>
            <el-button
              type="primary"
              @click="addOrUpdateHandle()"
            >新增</el-button>
            <el-button
              v-if="isAuth('product:attr:delete')"
              type="danger"
              @click="deleteHandle()"
              :disabled="dataListSelections.length <= 0"
            >批量删除</el-button>
          </el-form-item>
        </el-form>
        <el-table
          :data="dataList"
          border
          v-loading="dataListLoading"
          @selection-change="selectionChangeHandle"
          style="width: 100%;"
        >
          <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
          <el-table-column prop="id" header-align="center" align="center" label="id"></el-table-column>
          <el-table-column prop="name" header-align="center" align="center" label="属性名"></el-table-column>
          <el-table-column
            v-if="attrtype == 1"
            prop="searchType"
            header-align="center"
            align="center"
            label="可检索"
          >
            <template slot-scope="scope">
              <i class="el-icon-success" v-if="scope.row.searchType==1"></i>
              <i class="el-icon-error" v-else></i>
            </template>
          </el-table-column>
          <el-table-column prop="valueType" header-align="center" align="center" label="值类型">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.valueType==0">单选</el-tag>
              <el-tag v-else>多选</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="icon" header-align="center" align="center" label="图标"></el-table-column>
          <el-table-column prop="valueSelect" header-align="center" align="center" label="可选值">
            <template slot-scope="scope">
              <el-tooltip placement="top">
                <div slot="content">
                  <span v-for="(i,index) in scope.row.valueSelect.split(';')" :key="index">{{i}}<br/></span>
                </div>
                <el-tag>{{scope.row.valueSelect.split(";")[0]+" ..."}}</el-tag>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="enable" header-align="center" align="center" label="启用">
            <template slot-scope="scope">
              <i class="el-icon-success" v-if="scope.row.enable==1"></i>
              <i class="el-icon-error" v-else></i>
            </template>
          </el-table-column>
          <el-table-column prop="categoryName" header-align="center" align="center" label="所属分类"></el-table-column>
          <el-table-column
            v-if="attrtype == 1"
            prop="groupName"
            header-align="center"
            align="center"
            label="所属分组"
          ></el-table-column>
          <el-table-column v-if="attrtype == 1" prop="showDesc" header-align="center" align="center" label="快速展示">
            <template slot-scope="scope">
              <i class="el-icon-success" v-if="scope.row.showDesc==1"></i>
              <i class="el-icon-error" v-else></i>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            width="150"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
              <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
        <!-- 弹窗, 新增 / 修改 -->
        <add-or-update
          :type="attrtype"
          v-if="addOrUpdateVisible"
          ref="addOrUpdate"
          @refreshDataList="getDataList"
        ></add-or-update>
      </div>
    </el-col>
  </el-row>
</template>

<script>
//这里可以导入其他文件(比如:组件,工具js,第三方插件js,json文件,图片文件等等)
//例如:import 《组件名称》 from '《组件路径》';
import Category from "../common/category";
import AddOrUpdate from "./attr-add-or-update";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: { Category, AddOrUpdate },
  props: {
    attrtype: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      catId: 0,
      type: 1,
      dataForm: {
        key: ""
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false
    };
  },
  activated() {
    this.getDataList();
  },
  methods: {
    //感知树节点被点击
    treenodeclick(data, node, component) {
      if (node.level == 3) {
        this.catId = data.catId;
        this.getDataList(); //重新查询
      }
    },
    getAllDataList(){
      this.catId = 0;
      this.getDataList();
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      let type = this.attrtype == 0 ? "sale" : "base";
      this.$http({
        url: this.$http.adornUrl(`/product/attr/${type}/list/${this.catId}`),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          key: this.dataForm.key
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id);
      });
    },
    // 删除
    deleteHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map(item => {
            return item.id;
          });
      this.$confirm(
        `确定对[id=${ids.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        this.$http({
          url: this.$http.adornUrl("/product/attr/delete"),
          method: "post",
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    }
  }
};
</script>
<style scoped>
</style>

原文地址:https://blog.csdn.net/m0_46695127/article/details/142747283

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!