public List<Map<String, Object>> getCatalogTree() {
// MarketCatalog实体类有id,name,parent_id,status属性
MarketCatalog query = new MarketCatalog();
// tag实体类属性id,name,parent_id,Mapper从tag_system表中取出数据
List<Tag> allTagList = marketCatalogMapper.getList(query);
Map<Long, List<Tag>> tagListByParent = new HashMap<>();
allTagList.forEach(tag -> {
List<Tag> list = tagListByParent.get(tag.getParent_id());
if(list == null) {
list = new ArrayList<>();
tagListByParent.put(tag.getParent_id(), list);
}
list.add(tag);
});
List<Map<String, Object>> list = getCatalogChildren(-1L, tagListByParent);
return list;
}
private List<Map<String, Object>> getCatalogChildren(Long parentId, Map<Long, List<Tag>> tagListByParent) {
List<Tag> list = tagListByParent.get(parentId);
List<Map<String, Object>> result = new ArrayList<>();
if (list != null) {
list.forEach(tag -> {
JSONObject node = (JSONObject) JSONObject.toJSON(tag);
List<Map<String, Object>> children = getCatalogChildren(tag.getId(), tagListByParent);
if (children.size() > 0) {
node.put("children", children);
}
result.add(node);
});
}
return result;
}
mapper中:
<select id="getList" parameterType="jh.multi_tenant.entity.market.MarketCatalog"
resultType="jh.multi_tenant.market.entity.Tag">
select
id,name,parent_id
from tag_system
<where>
catalogue ='tag_quota'
<if test="parent_id != null and parent_id != ''">
and parent_id=#{parent_id}
</if>
</where>
order by tag_index
</select>
tag_system表结构: