java easyui 树型结构 查询 封装

阅读更多

 

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

/**
 * 查询所有,返回菜单树
 * @return	List
 */
public List getTreeListAll() {
	List menuList = menuDao.getListAll();
	List 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 treeNodeVos = new ArrayList();
		Map map = new LinkedHashMap();
		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 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;
}

 

你可能感兴趣的:(java,easyui,树型结构,查询,封装)