1.创建实体,这是排序的基本字段,其他字段自定义增加
import java.util.List; import org.springframework.data.annotation.Transient; public class HierachyDeviceModel { private Integer hierachy_id; private Integer parent_hid; private String parent_name; private Integer hierachy; /** * 指定同级别的顺序 */ private Integer sort; /** * org.springframework.data.annotation.Transient * NOT:javax.persistence.Transient */ @Transient private List<HierachyDeviceModel> children; public Integer getHierachy_id() { return hierachy_id; } public void setHierachy_id(Integer hierachy_id) { this.hierachy_id = hierachy_id; } public Integer getParent_hid() { return parent_hid; } public void setParent_hid(Integer parent_hid) { this.parent_hid = parent_hid; } public String getParent_name() { return parent_name; } public void setParent_name(String parent_name) { this.parent_name = parent_name; } public Integer getHierachy() { return hierachy; } public void setHierachy(Integer hierachy) { this.hierachy = hierachy; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public List<HierachyDeviceModel> getChildren() { return children; } public void setChildren(List<HierachyDeviceModel> children) { this.children = children; } }
2.获取树形结构
//获取所有实体数据 List<HierachyDeviceModel> hdmList = hdmMongo.findAll(); //获取顶层模型 List<HierachyDeviceModel> levelTopModel = new ArrayList<HierachyDeviceModel>(); for(HierachyDeviceModel hdm : hdmList) { if(hdm.getParent_hid() == 0) { levelTopModel.add(hdm); } } //设置树形结构 for(HierachyDeviceModel topModel : levelTopModel) { topModel.setChildren(getChildrens(topModel, hdmList)); //hdmList } //对顶层实体数据排序 levelTopModel.sort(new Comparator<HierachyDeviceModel>() { @Override public int compare(HierachyDeviceModel o1, HierachyDeviceModel o2) { return (o1.getSort() == null ? 0 : o1.getSort()) - (o2.getSort() == null ? 0 : o2.getSort()); }}); //
return levelTopModel;
3.实现树形结构
/** * * @param levelTop * @param allModels * @return */ private List<HierachyDeviceModel> getChildrens(HierachyDeviceModel levelTop, List<HierachyDeviceModel> allModels){ // List<HierachyDeviceModel> children = new ArrayList<HierachyDeviceModel>(); //递归实现树形结构 for(HierachyDeviceModel model : allModels) { if(model.getParent_hid().equals(levelTop.getHierachy_id())) { model.setChildren(getChildrens(model, allModels)); children.add(model); } } //对每层进行排序 children.sort(new Comparator<HierachyDeviceModel>() { @Override public int compare(HierachyDeviceModel o1, HierachyDeviceModel o2) { return (o1.getSort() == null ? 0 : o1.getSort()) - (o2.getSort() == null ? 0 : o2.getSort()); }}); return children; }
4.数据例子
标签:return,springboot,parent,创建,多级,hierachy,Integer,public,getSort From: https://www.cnblogs.com/anenyang/p/16924548.html