CREATE TABLE `pms_category` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT ‘分类id‘,
`name` char(50) DEFAULT NULL COMMENT ‘分类名称‘,
`parent_id` bigint(20) DEFAULT NULL COMMENT ‘父分类id‘,
`status` tinyint(4) DEFAULT NULL COMMENT ‘是否显示[0-不显示,1显示]‘,
`sort` int(11) DEFAULT NULL COMMENT ‘排序‘,
`icon` char(255) DEFAULT NULL COMMENT ‘图标地址‘,
`unit` char(50) DEFAULT NULL COMMENT ‘计量单位‘,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1433 DEFAULT CHARSET=utf8mb4 COMMENT=‘商品三级分类‘;
· 查询出parent_id为0的leve1的菜单
· 再根据leve1数据查询出子菜单
· 递归查询设值
#hutool工具包
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.2</version>
</dependency>
#mybatis-plus
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
package pyf.smilemall.product.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import lombok.Data;
/**
* 商品三级分类
*
* @author pyf
* @email pyf1653@163.com
* @date 2021-07-28 11:58:22
*/
@Data
@TableName("pms_category")
public class CategoryEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 分类id
*/
@TableId
private Long id;
/**
* 分类名称
*/
private String name;
/**
* 父分类id
*/
private Long parentId;
/**
* 是否显示[0-不显示,1显示]
*/
private Integer status;
/**
* 排序
*/
private Integer sort;
/**
* 图标地址
*/
private String icon;
/**
* 计量单位
*/
private String unit;
private transient List<CategoryEntity> childrens;
}
public List<CategoryEntity> listTree() {
//获取所有菜单
List<CategoryEntity> list=baseMapper.selectList(null);
//筛选一级数据
List<CategoryEntity> leve1Datas = list.stream()
.filter(o -> 0 == o.getParentId())
.map(menu->{
List<CategoryEntity> children = getChildren(menu, list);
menu.setChildrens(children);
return menu;
})
.sorted((menu1,menu2)->{
return (BeanUtil.isEmpty(menu1.getSort())?0:menu1.getSort())-(BeanUtil.isEmpty(menu2.getSort())?0:menu2.getSort());
})
.collect(Collectors.toList());
return leve1Datas;
}
/**
* 递归查询类
* @param menu
* @param list
* @return
*/
private List<CategoryEntity> getChildren(CategoryEntity menu, List<CategoryEntity> list) {
//筛选出父类
List<CategoryEntity> collect = list.stream()
.filter(o -> menu.getId().equals(o.getParentId()))
.map(cat-> {
List<CategoryEntity> children = getChildren(cat, list);
cat.setChildrens(children);
return cat;
})
.sorted(Comparator.comparingInt(menu2 -> (BeanUtil.isEmpty(menu2.getSort()) ? 0 : menu2.getSort())))
.collect(Collectors.toList());
return collect;
}
原文:https://www.cnblogs.com/pengyifeng/p/15135002.html