Three-level classification of goods and services (1)-code realization
First, take a look at the renderings:
The following is the classification table of the product classification stored in the database
Field explanation:
parent_cId
: The cat_id of the parent category.
cat_level
: Classification level
sort
: Priority, the smaller the higher the priority
analysis
Because the classification has a parent-child relationship, like a tree structure, it is necessary to add an attribute to the bean class of the classification to point to the sub-category.
/**
* 子分类List集合
*/
@TableField(exist = false)
private List<CategoryEntity> children;
In order to form a tree structure, it is necessary to increase the List collection to save the sub-categories. The TableFiled(exist = false)
function is to declare that this attribute does not exist in the database
Code
-
service:
public List<CategoryEntity> listWithTree() { //1、查出所有分类 List<CategoryEntity> entities = baseMapper.selectList(null); //2、组装成具有父子关系的树形结构(因为要形成树形结构,所以要有一个List的属性来存子分类) //2.1、找到所有一级分类(parentId == 0) List<CategoryEntity> level1Menus = entities.stream().filter(e -> e.getParentCid() == 0 ).map(e -> { //查找子分类 e.setChildren(getChildrens(e,entities)); return e; }).sorted((e1,e2) -> { //排序 return (e1.getSort()==null?0:e1.getSort()) -(e2.getSort()==null?0:e2.getSort()); }).collect(Collectors.toList()); return level1Menus; }
-
Recursive method:
/** * 递归地在所有分类中找到当前分类的子分类 * @param currentMenu * @param all * @return */ private List<CategoryEntity> getChildrens(CategoryEntity currentMenu,List<CategoryEntity> all) { //找到所有子分类并加入到子分类的List中 List<CategoryEntity> children = all.stream().filter(e -> { return e.getParentCid().intValue() == currentMenu.getCatId().intValue(); }).map(e -> { //继续找每个子分类的子分类 e.setChildren(getChildrens(e,all)); return e; }).sorted((e1,e2) -> { //排序 return (e1.getSort()==null?0:e1.getSort()) -(e2.getSort()==null?0:e2.getSort()); }).collect(Collectors.toList()); return children; }
to sum up