java递归生成树

public List  getAllCommType(){
  List treeList=new ArrayList();
  //取到父节点id为0,只有一个
  List typeList=commType.getAllCommodityType();
  for(Commodity_type type :typeList){
   Tree tree=new Tree();
   tree.setId(type.getType_id()+"");
   tree.setPid(type.getParent_id());
   tree.setText(type.getName());
   List childList=commType.listChildren(type);
   if(childList.size()>0){
    tree.setState("close");
    tree.setChildren(getAllTreeList(childList));
   }
   treeList.add(tree);
  }
  
  return treeList;
 }
 


commType.getAllCommodityType()的查询语句如下:

select * from commodity_type where parent_id=0

commType.listChildren(type)的查询语句如下:

select * from commodity_type where parent_id=#{type_id}


 /**
  * 加载子树(递归加载子子...树)
  * @param subTreeList
  * @return
  */
 public List getAllTreeList(List subTreeList) {
  List treeList = new ArrayList();
  for(Commodity_type type : subTreeList) {
   Tree tree = new Tree();
   tree.setId(type.getType_id()+"");
   tree.setPid(type.getParent_id());
   tree.setText(type.getName());
   List _subTreeList= commType.listChildren(type);
   if (_subTreeList.size() > 0) {
    tree.setState("closed");
    tree.setChildren(getAllTreeList(_subTreeList));
   }
   
   treeList.add(tree);
  }
  return treeList;
 }

你可能感兴趣的:(java)