查询:
@Override
public List<ItemCat> findItemCatList(Integer level) {
Map<Integer, List<ItemCat>> map = getMap();
if(level == 1)
return map.get(0);
else if(level == 2)
return getTwoList(map);
else
return getThreeList(map);
}
/**
* 获取1/2/3级菜单
*/
private List<ItemCat> getThreeList(Map<Integer, List<ItemCat>> map) {
List <ItemCat> oneList = getTwoList(map);
for (ItemCat oneItemCat : oneList) {
List<ItemCat> twoList = map.get(oneItemCat.getId());
if (twoList == null) {
continue;
}
for (ItemCat twoItemCat : twoList) {
List<ItemCat> threeList = map.get(twoItemCat.getId());
twoItemCat.setChildren(threeList);
}
}
return oneList;
}
/**
* 获取1、2级菜单
*/
private List<ItemCat> getTwoList(Map<Integer, List<ItemCat>> map) {
List<ItemCat> oneList = map.get(0);
for(ItemCat oneItemCat : oneList) {
int key = oneItemCat.getId();
List<ItemCat> twoList = map.get(key);
oneItemCat.setChildren(twoList);
}
return oneList;
}
/**
* 获取三级菜单Map
* map(parentId,当前id的子菜单)
*
* 1.判断map中是否存在key
* 2.如果不存在 准备新List 并存入
* 如果存在 直接存会覆盖 先获取list 追加后再存入
*/
public Map<Integer, List<ItemCat>> getMap() {
HashMap<Integer, List<ItemCat>> map = new HashMap<>();
List<ItemCat> list = itemCatMapper.selectList(null);
for (ItemCat ic : list) {
int key = ic.getParentId();
if (map.containsKey(key)) {
map.get(key).add(ic);
} else{
List<ItemCat> child = new ArrayList<>();
child.add(ic);
map.put(key,child);
}
}
return map;
}
删除:
@Override
@Transactional
public void updateStatus(ItemCat ic) {
itemCatMapper.updateStatus(ic);
}
/**
* 删除ItemCat
* 如果存在子级 也要删除
*/
@Override
@Transactional
public void deleteIC(ItemCat ic) {
if(ic.getLevel() == 3) {
itemCatMapper.deleteById(ic.getId());
}
else if(ic.getLevel() == 2) {
int twoId = ic.getId();
//查询三级菜单并删除
QueryWrapper<ItemCat> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("parent_id", twoId);
itemCatMapper.delete(queryWrapper);
//删除自己
itemCatMapper.deleteById(twoId);
}
else {
int oneId = ic.getId();
//查询二级菜单
QueryWrapper<ItemCat> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("parent_id", oneId);
List<Object> twoIdList = itemCatMapper.selectObjs(queryWrapper);
if (twoIdList.size() == 0) {
itemCatMapper.deleteById(oneId);
} else {
//delete from item_cat where parent_id in ()
// or id in ()
queryWrapper.clear();
queryWrapper.in("parent_id", twoIdList)
.or()
.in("id", twoIdList)
.or()
.eq("id", oneId);
itemCatMapper.delete(queryWrapper);
}
}
}