Java+oracle树查询实现easyui中tree使用的json
1.前端页面使用easyui的tree
1 <ul id="some_tree"></ul>
2
3 $("#some_tree").tree({
4 url:'/getTreeJsonData.action',
5 lines :true,
6 onClick :function(node){
7 //TODO : after click
8 }
9 });
2.创建TreeJson的dto
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONObject;
/**
* easui中的tree_data.json数据,只能有一个root节点
* [{
"id":1,
"text":"Folder1",
"iconCls":"icon-save",
"children":[{
"text":"File1",
"checked":true
}]
}]
* 提供静态方法formatTree(List<TreeJson> list) 返回结果
* TreeJson.formatTree(treeJsonlist) ;
* @author lwb
*
*/
public class TreeJson implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String id ;
private String pid ;
private String text ;
private String iconCls ;
private String state ;
private String checked ;
private JSONObject attributes = new JSONObject() ;
private List<TreeJson> children = new ArrayList<TreeJson>() ;
/******** setter and getter **********/
public static List<TreeJson> formatTree(List<TreeJson> list) {
TreeJson root = new TreeJson();
TreeJson node = new TreeJson();
List<TreeJson> treelist = new ArrayList<TreeJson>();// 拼凑好的json格式的数据
List<TreeJson> parentnodes = new ArrayList<TreeJson>();// parentnodes存放所有的父节点
if (list != null && list.size() > 0) {
root = list.get(0) ;
//循环遍历oracle树查询的所有节点
for (int i = 1; i < list.size(); i++) {
node = list.get(i);
if(node.getPid().equals(root.getId())){
//为tree root 增加子节点
parentnodes.add(node) ;
root.getChildren().add(node) ;
}else{//获取root子节点的孩子节点
getChildrenNodes(parentnodes, node);
parentnodes.add(node) ;
}
}
}
treelist.add(root) ;
return treelist ;
}
private static void getChildrenNodes(List<TreeJson> parentnodes, TreeJson node) {
//循环遍历所有父节点和node进行匹配,确定父子关系
for (int i = parentnodes.size() - 1; i >= 0; i--) {
TreeJson pnode = parentnodes.get(i);
//如果是父子关系,为父节点增加子节点,退出for循环
if (pnode.getId().equals(node.getPid())) {
pnode.setState("closed") ;//关闭二级树
pnode.getChildren().add(node) ;
return ;
} else {
//如果不是父子关系,删除父节点栈里当前的节点,
//继续此次循环,直到确定父子关系或不存在退出for循环
parentnodes.remove(i) ;
}
}
}
}
3.使用oracle树查询,查询需要构建树的记录,转换成TreeJson对象
<typeAlias alias="treeJson" type="TreeJson"/>
<select id="queryATree" resultClass="treeJson" >
SELECT t.id,
t.text,
t.pid,
t.iconcls
FROM table t
start with t.pid= 0
connect by t.pid= prior t.id
ORDER SIBLINGS BY T.id
</select>
4.组合
oracle查询结果为List<TreeJson>,使用TreeJson对象的静态方法formatTree将其转换成前台需要的tree_data.json数据返回到前台
List<TreeJson> list = TreeJson.formatTree(dao.queryATree()) ;