在树结构中:数据库查出根节点,而子节点需要根节点for循环查出:有几个常见的问题,
·假如根节点的数据量比较大,那么子节点需要大量的数据库查询操作,
1.浪费数据库资源,
2.频繁对数据库进行操作,导致数据库效率低下,速度卡顿
.........
解决:将子节点数据一次性查出,然后通过Map来做临时存储,然后通过根节点做key来取子节点。
代码案例:
public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, HttpServletResponse response) { List<Map<String, Object>> mapList = Lists.newArrayList(); SysDepartment sd = new SysDepartment(); sd.setDeptStatus("01"); List<SysDepartment> list = sysDepartmentService.findList(sd);//获取所有部门节点 Map<String, Object> map = null; //add by dengbinsheng start List<SysPost> postList = sysPostDao.findList(new SysPost());//获取所有岗位子节点 Map<String,List<SysPost>> postMap = new HashMap<String,List<SysPost>>();//创建临时存储子节点的Map数据 String deptId = ""; if (postList != null && postList.size()>0) { for (int i=0; i<postList.size();i++) { SysPost post = postList.get(i); deptId = post.getDepartmentId(); if(StringUtils.isNotBlank(deptId)) { if (postMap.containsKey(deptId)) { postMap.get(deptId).add(post); } else { List<SysPost> postList2 = new ArrayList<SysPost>(); postList.add(post); postMap.put(deptId, postList2); } } } } //add by dengbinsheng end for (int i=0; i<list.size(); i++){ SysDepartment e = list.get(i); // SysDepartmentPost sdp = new SysDepartmentPost(); // sdp.setDeptId(e.getId()); // List<SysPost> listPsot = sysPostDao.findSysPostForDepartId(e.getId()); List<SysPost> listPsot = postMap.get(e.getId());//通过部门节点获取临时的岗位子节点 if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){ map = Maps.newHashMap(); map.put("id", e.getId()); map.put("pId", e.getParentId()); map.put("name", e.getName()); map.put("pIds", e.getParentIds()); mapList.add(map); if(listPsot != null && listPsot.size()>0){ for(int j = 0; j<listPsot.size();j++){ map = Maps.newHashMap(); SysPost sp = listPsot.get(j); map.put("id", sp.getId()); map.put("pId", e.getId()); map.put("name","【岗】"+sp.getName()); map.put("pIds", e.getParentIds()); mapList.add(j,map); } e.setSysPost(listPsot); } } } return mapList; }
重点再于Map数据储存,根据业务参考。