1.數據庫sql語句
create table company(
company_id int not null auto_increment,
parent_company_id int null,
name varchar(128) null,
phone varchar(16) null,
constraint PK_COMPANY primary key clustered (company_id)
);
2.查詢語句DAO
public List<Company> getAllCompany() {
List<Company> companies=null;
String hql = "select c from Company c";
Query query=getEntityManager().createQuery(hql);
companies=query.getResultList();
return companies;
}
3.創建返回實體
public class CompanyTreeVo{
private Integer companyId;
private String name;
private String phone;
private List<CompanyTreeVo> children;//...getter/setter..}
3.組裝成tree-Service
public CompanyTreeVo findAllCompanyName() {
List<Company> companies = companyDao.getAllCompany();
if(companies!=null&&companies.size()>0) {
Map<Integer, Company> objectMap = new HashMap<>();
Map<Integer, List<Integer>> childMap = new HashMap<>();
Integer rootId = CompanyFactory.checkTree(companies, childMap, objectMap);
CompanyTreeVo treeVo = CompanyFactory.initTreeCompany(rootId, childMap, objectMap);
return treeVo;
}else{
return null;
}}
public static Integer checkTree(List<Company> companies,Map<Integer,List<Integer>> childMap,Map<Integer,Company> objectMap){
Map<Integer,CompanyMenuVo> maps=new HashMap<>();
Integer rootId=null;
CompanyMenuVo companyMenuVo=null;
if(companies!=null &&companies.size()>0){//判斷查詢過來的值不爲空
for(Company company :companies){//遍歷查詢的值
objectMap.put(company.getCompanyId(),company);
Integer parentId = company.getParentCompanyId();//獲取每個對象的父id
if(parentId != null){//如果父id不爲null則進行下面操作
List<Integer> list = childMap.get(parentId);//獲取父id的集合是否初始化
if(list==null){
list = new ArrayList<>();
}
//將公司id添加集合中
list.add(company.getCompanyId());
//將集合添加到key爲父id的map中
childMap.put(parentId,list);
}else{//父id初始化操作
rootId=company.getCompanyId();
}
}
}
return rootId;
}
public static CompanyTreeVo initTreeCompany(Integer rootId,Map<Integer,List<Integer>> childMap, Map<Integer,Company> objectMap){
CompanyTreeVo rootVo = new CompanyTreeVo();
List<CompanyTreeVo> children = new ArrayList<>();
Company company = objectMap.get(rootId);
//將實體對象轉換爲vo對象
initCompanyTreeVo(rootVo, company);
List<Integer> childList = childMap.get(rootId);
if(childList!=null&&childList.size()>0){
for(Integer childId:childList){
//遞歸將數據轉入list集合中
CompanyTreeVo childTreeVo = initTreeCompany(childId, childMap, objectMap);
childTreeVo.setParentCompanyName(company.getName());
children.add(childTreeVo);
}
}
rootVo.setChildren(children);
return rootVo;
}
//將實體對象轉換爲vo對象
public static void initCompanyTreeVo(CompanyTreeVo treeVo,Company company){
treeVo.setCompanyId(company.getCompanyId());
treeVo.setName(company.getName());
treeVo.setParentCompanyId(company.getParentCompanyId());
}