/优化封装Map集合
public Map<Integer, List<ItemCat>> getMap() {
Map<Integer,List<ItemCat>>map=new HashMap<>();
//查询数据库的所有的记录
List<ItemCat> list = itemCatMapper.selectList(null);
for (ItemCat itemCat:list){
int key=itemCat.getParentId();
if (map.containsKey(key)){//true 有数据 将自己追加
map.get(key).add(itemCat);
}else{//false 没有数据 准备新集合,添加数据
List<ItemCat> childrenList=new ArrayList<>();
childrenList.add(itemCat);
map.put(key,childrenList);
}
}
return map;
}
@Override
public List<ItemCat> findItemCatList( Integer level) {
long l = System.currentTimeMillis();
//获取数据信息
Map<Integer,List<ItemCat>> map =getMap();
if (level==1){//只获取一级菜单数据
return map.get(0);
}
if (level==2){
return gettwoList(map);
}
List<ItemCat> list=getThreeList(map);
long l1 = System.currentTimeMillis();
System.out.println("运行时间"+(l1-l)+"毫秒");
//获取1-2-3级数据
return list;
private List<ItemCat> gettwoList(Map<Integer, List<ItemCat>> map) {
//获取一级数据
List<ItemCat> oneList=map.get(0);
for (ItemCat oneItemCat:oneList){
//根据一级ID查询二级集合
int key=oneItemCat.getId();
List<ItemCat> twoList=map.get(key);
//将二级数据封装到一级中
oneItemCat.setChildren(twoList);
}
return oneList;
}
private List<ItemCat> getThreeList(Map<Integer, List<ItemCat>> map) {
//1.获取以及和二级的数据
List<ItemCat> oneList=gettwoList(map);
for (ItemCat oneItemCat:oneList){
List<ItemCat> twoList=oneItemCat.getChildren();
if (twoList==null){
//说明 该下级没有二级数据,所以跳过本次循环进入下一次
continue;
}
for (ItemCat twoItemCat:twoList){
//查询三级数据,使用二级ID
int key =twoItemCat.getId();
List<ItemCat> threeList = map.get(key);
twoItemCat.setChildren(threeList);
}
}
return oneList;
}
删除数据
@Override
@Transactional
public void deleteItemCat(ItemCat itemCat) {
if (itemCat.getLevel()==3){
itemCatMapper.deleteById(itemCat.getId());
return;
}
if (itemCat.getLevel()==2){
int twoId=itemCat.getId();
QueryWrapper<ItemCat> queryWrapper=new QueryWrapper<>();
queryWrapper.eq("parent_id", twoId);
itemCatMapper.delete(queryWrapper);
itemCatMapper.deleteById(twoId);
return;
}
int oneId=itemCat.getId();
QueryWrapper<ItemCat> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("parent_id", oneId);
List twoList = itemCatMapper.selectObjs(queryWrapper);
if (twoList.size()==0){
itemCatMapper.deleteById(oneId);
}else{
queryWrapper.clear();
queryWrapper.in("parent_id", twoList)
.or()
.in("id", twoList)
.or()
.eq("id", oneId);
itemCatMapper.deleteById(queryWrapper);
}
}