实体类:
public class AddressTreeDto { private Long id; private String text;//位置名称 private Long pId;//上一级 private Integer able; private List<AddressTreeDto> nodes; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Long getpId() { return pId; } public void setpId(Long pId) { this.pId = pId; } public Integer getAble() { return able; } public void setAble(Integer able) { this.able = able; } public List<AddressTreeDto> getNodes() { return nodes; } public void setNodes(List<AddressTreeDto> nodes) { this.nodes = nodes; } }
Service接口:
public interface AddressService { //查询所有存放地,返回TreeView数据格式 List<AddressTreeDto> getAddressTree(); }
ServiceImpl实现类
public class AddressServiceImpl implements AddressService { @Autowired private AddressMapper addressMapper; private List<AddressTreeDto> getChild(Long id, List<AddressTreeDto> rootAddress) { // 子菜单 List<AddressTreeDto> childList = new ArrayList<>(); for (AddressTreeDto treeDto : rootAddress) { // 遍历所有节点,将父菜单id与传过来的id比较 if (treeDto.getpId()!=null) { if (treeDto.getpId().equals(id)) { childList.add(treeDto); } } } // 把子菜单的子菜单再循环一遍 for (AddressTreeDto treeDto: childList) { // 没有url子菜单还有子菜单---判断还有子菜单 if(getIds(treeDto.getId())!=null){ //递归 treeDto.setNodes(getChild(treeDto.getId(),rootAddress)); } } // 递归退出条件 if (childList.size() == 0) { return null; } return childList; } @Override public List<AddressTreeDto> getAddressTree() { // 原始的数据 List<AddressTreeDto> rootAddress = addressMapper.selectTree(Constants.ABLE_CONFIG.DEFAULT_ABLE); // 查看结果 for (AddressTreeDto treeDto1 : rootAddress) { System.out.println(treeDto1); } // 最后的结果 List<AddressTreeDto> addressList = new ArrayList<>(); // 先找到所有的一级菜单 for (int i = 0; i < rootAddress.size(); i++) { // 一级菜单没有parentId if (rootAddress.get(i).getpId()==0) { addressList.add(rootAddress.get(i)); } } // 为一级菜单设置子菜单,getChild是递归调用的 for (AddressTreeDto treeDto1 : addressList) { treeDto1.setNodes(getChild(treeDto1.getId(), rootAddress)); } return addressList; } }