【java】树形菜单的实现
/**
* 商品三级分类
*
*/
@Data
@TableName("pms_category")
public class CategoryEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 分类id
*/
@TableId
private Long catId;
/**
* 分类名称
*/
private String name;
/**
* 父分类id
*/
private Long parentCid;
/**
* 层级
*/
private Integer catLevel;
/**
* 是否显示[0-不显示,1显示]
*/
@TableLogic(value = "1", delval = "0")
private Integer showStatus;
/**
* 排序
*/
private Integer sort;
/**
* 图标地址
*/
private String icon;
/**
* 计量单位
*/
private String productUnit;
/**
* 商品数量
*/
private Integer productCount;
/**
* 形成树型结构
*/
@JsonInclude(value = JsonInclude.Include.NON_EMPTY)
@TableField(exist = false)
private List<CategoryEntity> children;
}
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<CategoryEntity> page = this.page(
new Query<CategoryEntity>().getPage(params),
new QueryWrapper<CategoryEntity>()
);
return new PageUtils(page);
}
/**
* 树型显示
*
* @return
*/
@Override
public List<CategoryEntity> listWithTree() {
List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
List<CategoryEntity> treeMenus = categoryEntities.stream().filter((categoryEntity) -> {
return categoryEntity.getParentCid() == 0;
}).sorted((menu1, menu2) -> {
return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
}).map((menu) -> {
menu.setChildren(getChildren(menu, categoryEntities));
return menu;
}).collect(Collectors.toList());
return treeMenus;
}
private List<CategoryEntity> getChildren(CategoryEntity rootMenu, List<CategoryEntity> allMenus) {
List<CategoryEntity> childrenList = allMenus.stream().filter(categoryEntity -> {
return categoryEntity.getParentCid().equals(rootMenu.getCatId());
}).map(menu -> {
menu.setChildren(getChildren(menu, allMenus));
return menu;
}).sorted((m1, m2) -> {
return (m1.getSort() == null ? 0 : m1.getSort()) - (m2.getSort() == null ? 0 : m2.getSort());
}).collect(Collectors.toList());
return childrenList;
}
@Override
public void removeMenus(List<Long> asList) {
System.out.println("删除的数据为: ++ ++++" + asList);
// 逻辑删除
int result = baseMapper.deleteBatchIds(asList);
if (result < 0) {
throw new RRException("删除失败");
}
}
/**
* 寻找一个category的全路径 example [2.3,6]
*
* @param catelogId
* @return
*/
@Override
public Long[] findCategoryPath(Long catelogId) {
List<Long> path = new ArrayList<>();
List<Long> parentPath = findParentPath(catelogId, path);
Collections.reverse(parentPath);
return parentPath.toArray(new Long[parentPath.size()]);
}
private List<Long> findParentPath(Long catelogId, List<Long> path) {
path.add(catelogId);
CategoryEntity categoryEntity = baseMapper.selectById(catelogId);
if (categoryEntity.getParentCid() != 0) {
findParentPath(categoryEntity.getParentCid(), path);
}
return path;
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)