谷粒商城基础篇


1.商品三级分类(递归树形)

CategoryEntity实体类加一个children字段来展示子树

public class CategoryEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
	 * 所有子分类
	 */
	@JsonInclude(JsonInclude.Include.NON_EMPTY)
	@TableField(exist = false)
	private List<CategoryEntity> children;

}

商品实现类使用stream流实现三级分类

@Override
public List<CategoryEntity> listWithTree() {

    //1、查询出所有分类
    List<CategoryEntity> entities = super.baseMapper.selectList(null);

    //2、组装成父子的树形结构

    //2.1)、找到所有一级分类
    List<CategoryEntity> levelMenus = entities.stream()
            .filter(e -> e.getParentCid() == 0)
            .map((menu) -> {
                menu.setChildren(getChildrens(menu, entities));
                return menu;
            })
            .sorted((menu, menu2) -> {
                return (menu.getSort() == null ? 0 : menu.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
            })
            .collect(Collectors.toList());

    return levelMenus;
}
//递归查找所有菜单的子菜单
private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {

    List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
        return categoryEntity.getParentCid().equals(root.getCatId());
    }).map(categoryEntity -> {
        //1、找到子菜单(递归)
        categoryEntity.setChildren(getChildrens(categoryEntity, all));
        return categoryEntity;
    }).sorted((menu, menu2) -> {
        //2、菜单的排序
        return (menu.getSort() == null ? 0 : menu.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
    }).collect(Collectors.toList());

    return children;

}

  目录