1 构造一个树结构
@Entity
@Table(name = "DW_META_MMDIR")
public class DwMmDirVO {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "PK_DIR", length = 36, nullable = false, columnDefinition = "CHAR(36)")
private String pkDir;
@Column(name = "PK_PARENT", length = 36, columnDefinition = "CHAR(36)")
private String pkParent;
@Column(name = "NAME", length = 100)
private String name;
@Transient
private String path; //把路径带进去
@Transient
List<DwMmDirVO> children;
2 递归回去树
public List<DwMmDirVO> getDwMmDirTree() {
// 定义根节点
List<DwMmDirVO> rootVO = new ArrayList<DwMmDirVO>();
try {
// 查询所有节点
List<DwMmDirVO> vos = dwMmDirDAO.findALLList();
for (DwMmDirVO vo : vos) {
if (StringUtils.isBlank(vo.getPkParent())) {
vo.setPath(DwConst.PATH + vo.getName());
rootVO.add(vo);
}
}
// 获取根下面节点
for (DwMmDirVO vo : rootVO) {
List<DwMmDirVO> childList = getChildNode(vo, vos);
vo.setChildren(childList);
}
} catch (Exception e) {
e.getStackTrace();
}
return rootVO;
}
/**
*
* @Title: getChildNode
* @Description: TODO(获取所有子节点)
* @param @param parentVO
* @param @param vos
* @param @return 参数
* @return List<DwMmDirVO> 返回类型
* @throws
*/
private List<DwMmDirVO> getChildNode(DwMmDirVO parentVO, List<DwMmDirVO> vos) {
List<DwMmDirVO> childList = new ArrayList<DwMmDirVO>();
for (DwMmDirVO vo : vos) {
if (StringUtils.isNotBlank(vo.getPkParent())) {
if (vo.getPkParent().equals(parentVO.getPkDir())) {
vo.setPath(DwConst.PATH + parentVO.getName() + DwConst.PATH +
vo.getName());
childList.add(vo);
}
}
}
// 递归获取子节点
for (DwMmDirVO vo : childList) {
vo.setChildren(getChildNode(vo, vos));
}
if (childList.size() == 0) {
return new ArrayList<DwMmDirVO>();
}
return childList;
}
3 根据类型获取path
public String getPath(String classifyKey) {
DwMmDirVO vo = null;
try {
List<DwMmDirVO> vos = dwMmDirDAO.findALLList();
for(DwMmDirVO dirvo:vos){
if(dirvo.getPkDir().equals(classifyKey)){
vo = dirvo;
}
}
vo.setPath(DwConst.PATH + vo.getName());
vo = getParentObject(vo,vos);
} catch (Exception e) {
e.getStackTrace();
}
return vo.getPath();
}
/**
*
* @Title: getParentObject
* @Description: TODO(获取父节点)
* @param @param vo
* @param @param vos
* @param @return 参数
* @return String 返回类型
* @throws
*/
public DwMmDirVO getParentObject(DwMmDirVO vo,List<DwMmDirVO> vos) {
String path = vo.getPath();
if (StringUtils.isEmpty(vo.getPkParent())) {
return vo;
}
DwMmDirVO parentVO = vos.stream()
.filter(x -> x.getPkDir().equals(vo.getPkParent())).findFirst().get();
parentVO.setPath(DwConst.PATH + parentVO.getName() + path);
return getParentObject(parentVO,vos);
}