欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java easyui 树型结构 查询 封装

程序员文章站 2022-04-14 14:31:24
...

 

一次数据库查询,封装成树型结构数据 List<TreeNodeVo>

/**
 * 查询所有,返回菜单树
 * @return	List<TreeNodeVo>
 */
public List<TreeNodeVo> getTreeListAll() {
	List<Menu> menuList = menuDao.getListAll();
	List<TreeNodeVo> tempTreeNodeVos = new ArrayList();
	TreeNodeVo tempTreeNode;
	for (Menu menu : menuList) {
		tempTreeNode = new TreeNodeVo();
		tempTreeNode.setId(menu.getId());
		tempTreeNode.setParentId(menu.getParentId());
		tempTreeNode.setText(menu.getName());
		if ("1".equals(menu.getLeaf())) {
			tempTreeNode.setState("open");
		} else {
			tempTreeNode.setState("closed");
		}
		tempTreeNode.setUrl(menu.getUrl());
		tempTreeNodeVos.add(tempTreeNode);
	}

	if (tempTreeNodeVos != null) {
		List<TreeNodeVo> treeNodeVos = new ArrayList();
		Map<String, TreeNodeVo> map = new LinkedHashMap<String, TreeNodeVo>();
		for (TreeNodeVo tn : tempTreeNodeVos) {
			map.put(tn.getId(), tn);
		}

		TreeNodeVo treeNodeVo;
		TreeNodeVo pTreeNodeVo;
		for (String id : map.keySet()) {
			treeNodeVo = map.get(id);
			if (treeNodeVo.getParentId() == null) {
				treeNodeVos.add(treeNodeVo);
			} else {
				pTreeNodeVo = map.get(treeNodeVo.getParentId());
				List<TreeNodeVo> children = pTreeNodeVo.getChildren();
				if(children!=null){
					children.add(treeNodeVo);
				} else {
					children = new ArrayList();
					children.add(treeNodeVo);
					pTreeNodeVo.setChildren(children);
				}
			}
		}
		return treeNodeVos;
	}
	return null;
}

 

参考:

easyui tree 树 TreeNodeVo

http://happyqing.iteye.com/blog/2371178

将数据封装成树形结构,无限级深,

http://www.oschina.net/code/snippet_915857_22297

/**
 *  包装成树形结构 (全部属性)
 *  将数据封装成树形结构,无限级深,只需遍历两次 @param tree为List类型存放的初始VO对象。该vo类必须有id,parentId,children字段。children为List类型
 * @param tree
 * @return
 * @throws Exception
 */
public static List factorTree(List tree) throws Exception{
	if (tree != null) {
		List t_list = new ArrayList();
		Map map = new HashMap();
		for (Object o : tree) {
			Class clazz = o.getClass();
			Field id = clazz.getDeclaredField("id");
			if (!id.isAccessible()) {
				id.setAccessible(true);
			}
			Long lId = (Long) id.get(o);
			map.put(lId, o);
		}

		for (Object o : map.keySet()) {
			Long cId = (Long) o;
			Object obj = map.get(cId);
			Class clazz = obj.getClass();
			Field pId = clazz.getDeclaredField("parentId");
			if (!pId.isAccessible()) {
				pId.setAccessible(true);
			}
			Long id = (Long) pId.get(obj);
			if (id == null) {
				t_list.add(obj);
			} else {
				Object object = map.get(id);
				Class clazz1 = object.getClass();
				Field children = clazz1.getDeclaredField("children");
				if (!children.isAccessible()) {
					children.setAccessible(true);
				}
				List list = (List) children.get(object);
				if (CollectionUtils.isEmpty(list)) {
					list = new ArrayList();
				}
				list.add(obj);
				children.set(object, list);
			}
		}
		return t_list;
	}
	return null;
}