分类树

门户网站中商品分类具有层级关系。列如,电器—电视—8K超帅电视机。这些数据需要一开始就在页面上展示,所以通过分类树的方式将这些数据获取到。

1.数据结构——一定要有的字段

    private List<CourseType> children = new ArrayList<>();

    private Long pid;

2.创建controller

@RestController
@RequestMapping("/courseType")
public class CourseTypeController {

    @Autowired
    public ICourseTypeService courseTypeService;
    
    //查询课程分类树
    @RequestMapping(value="/treeData",method= RequestMethod.GET)
    public AjaxResult treeData(){
       List<CourseType> result = courseTypeService.treeData();
        //System.out.println(result);
       return AjaxResult.me().setResultObj(result);
    }
}

3.创建service

@Service
public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeMapper, CourseType> implements ICourseTypeService {

    //查询课程分类树  使用循环的方式去查询到所有的数据
    @Override
    //打上这个注解  优先当使用查询的时候优先使用缓存中的数据  如果缓存中没有再去查询数据库中数据  再放入到缓存中
    //RedisConstants.KEY_COURSE_TYPE_TREE 指定一个Redis的表(可以为多张表)  key为库的后缀(不重要)
    @Cacheable(cacheNames = RedisConstants.KEY_COURSE_TYPE_TREE,key = "'ALL'")
    public List<CourseType> treeData() {
        //使用方法获取到分类树
        List<CourseType> firstCourseType = getCourseTypes();
        //返回新数据
        return firstCourseType;
    }
    
    private List<CourseType> getCourseTypes() {
        //查询出所有课程分类  这个方法可以查询出所有的课程分类
        List<CourseType> courseTypes = baseMapper.selectList(null);
        //System.out.println(courseTypes);
        //创建一个集合用来接收所有的数据
        List<CourseType> firstCourseType = new ArrayList<>();
        //遍历所有的课程
        courseTypes.forEach(courseType -> {
            //判断  只有当pid为空或者为0的时候就是一级  不然为二级
            if(courseType.getPid() == null || courseType.getPid().longValue() == 0){
                //将所有的一级数据放入到集合中
                firstCourseType.add(courseType);
            }else {
                //不为一级课程就为子级课程  在通过遍历所有的子级课程  让它们自己去寻找自己的父级课程
                for (CourseType parentCourseType : courseTypes){
                    //使用判断  它们的pid能否找到id的对象并将自己放入到对应的父级的childen的字段中
                    if (courseType.getPid().longValue() == parentCourseType.getId().longValue()){
                        //如果循环的子级的Id能够找到对应的pid说明它为对应pid对象的儿子  将子级放入到父亲的chilren字段中
                        parentCourseType.getChildren().add(courseType);
                        break;
                    }
                }
            }
        });
        return firstCourseType;
    }
}

3.分类树的个人理解
3.1分类树可以应用在一些范围的选择上,通过层级结构的方式展示在页面
3.2所有的商品的根级组成一个集合
3.3循环方式的分类树,第一层遍历拿到所有的一级数据,然后将一级数据封装在一起,第二层遍历是遍历有的非一级数据,通过判断的方式将所有非一级数据放入到它们自己的父级对象的children字段的集合中去,从而获取到分类树

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值