需求:不使用递归查询出一棵树。

service层业务代码

@SuppressWarnings(“unchecked”)
public JsonRet getOrganizationList(HttpServletRequest request, HttpServletResponse response) {
LOG.d(
“getOrgnazationList”);
// 从Session得到用户信息
HttpSession session = request.getSession();
TuUser tuUser
= (TuUser) session.getAttribute(Constant.USER_INFO);
List
<TuOrganization> organizationList = tuOrganizationMapper.getOrganizationList(tuUser.getBranchNo());

Map<String, Object> item;
//获取根节点的集合
List<Map<String, Object>> root = new ArrayList<>();
Map
<String, Map<String, Object>> tempMap = new HashMap<>();
//子节点集合
List<Map<String, Object>> children;
for(TuOrganization o : organizationList) {
children
= new ArrayList<>();
item
= new HashMap<>();
item.put(
“id”, o.getId());
item.put(
“parentId”, o.getParentId());
item.put(
“created”, o.getCreateTime());
item.put(
“name”, o.getName());
item.put(
“sort”, o.getSort());
item.put(
“status”, o.getStatus());
item.put(
“children”, children);
//每次循环都将集合重新循环添加到父集合中
tempMap.put(o.getId(), item);
Map
<String, Object> parent = tempMap.get(o.getParentId());
if(null != parent) {
//父集合不为空时,获取下级集合
((List<Map<String, Object>>)parent.get(“children”)).add(item);
}
else {
//根集合
root.add(item);
}
}

Comparator<Map<String, Object>> comparator = new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
//根据sort字段进行排序
Integer i1 = ((Integer)o1.get(“sort”));
Integer i2
= ((Integer)o2.get(“sort”));
if(i1 > i2) {
return 1;
}
else if(i1 < i2) {
return -1;
}
//若sort字段相同的话,根据创建时间来进行排序
Date d1 = ((Date)o1.get(“created”));
Date d2
= ((Date)o2.get(“created”));
if(null == d1 || null == d2) return 0;
return d1.compareTo(d2);
}
};

Collections.sort(root, comparator);
for (Map.Entry<String, Map<String, Object>> entry : tempMap.entrySet()) {
Collections.sort(((List
<Map<String, Object>>)entry.getValue().get(“children”)), comparator);
}

return jsonResponse(root, Constants.CODE_SUCCESS, “成功”);
}

在循环内封装tempMap,然后直接就可以调用,是因为在SQL中对path做了排序,越往根级的组织越先被遍历到,或者可以直接遍历两次,第一次用来封装temMap,这样SQL语句中就不需要path排序,getOrganizationList SQL语句如下

  <select id="getOrganizationList" parameterType="java.lang.String" resultMap="BaseResultMap">
   select
    <include refid="Base_Column_List" />
    from tu_organization where branch_no = #{branchNo,jdbcType=VARCHAR} order by path
  </select>

数据库表结构

 

版权声明:本文为lvtao原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/lvtao/p/8683183.html