Java 获取列表树结构,递归删除子节点
数据库表结构 Model VO 查询树结构列表 递归删除子节点
数据库表结构
Model
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TBaseDept
{
private String id;
private String fdName;
private String fdCode;
private String fdLevel;
private String parentId;
private String parentName;
private String fdHier;
private String fdHierPath;
private String fdOne;
private String fdTwo;
private String fdThree;
private String fdStatus;
private Integer fdOrder;
}
VO
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TBaseDeptVO implements Serializable
{
private static final long serialVersionUID = 8599451909890724624L ;
private String id;
private String fdName;
private String fdCode;
private String fdLevel;
private String parentId;
private String parentName;
private String fdHier;
private String fdHierPath;
private String fdOne;
private String fdTwo;
private String fdThree;
private String fdStatus;
private Integer fdOrder;
private List < TBaseDeptVO > children;
}
查询树结构列表
public List < TBaseDeptVO > queryTree ( TBaseDept tBaseDept)
{
List < TBaseDept > tBaseDeptList = tBaseDeptDao. findByCriteria ( tBaseDept) ;
return buildTree ( tBaseDeptList, "0" ) ;
}
private List < TBaseDeptVO > buildTree ( List < TBaseDept > list, String parentId)
{
List < TBaseDeptVO > tree = new ArrayList < > ( ) ;
for ( TBaseDept child : list)
{
if ( child. getParentId ( ) . equals ( parentId) )
{
TBaseDeptVO tBaseDeptVO = new TBaseDeptVO ( ) ;
BeanUtil . copyProperties ( child, tBaseDeptVO) ;
List < TBaseDeptVO > children = buildTree ( list, child. getId ( ) ) ;
List < TBaseDeptVO > collect = children. stream ( ) . sorted ( Comparator . comparing ( TBaseDeptVO :: getFdOrder ) )
. collect ( Collectors . toList ( ) ) ;
tBaseDeptVO. setChildren ( collect) ;
tree. add ( tBaseDeptVO) ;
}
}
return tree;
}
递归删除子节点
public void deleteDept ( TBaseDept tBaseDept)
{
String id = tBaseDept. getId ( ) ;
List < String > ids = queryChildNodes ( id) ;
tBaseDeptService. delete ( ids) ;
}
private List < String > queryChildNodes ( String id)
{
List < String > ids = new ArrayList < > ( ) ;
TBaseDept dept = new TBaseDept ( ) ;
dept. setParentId ( id) ;
List < TBaseDept > childIds = tBaseDeptService. queryList ( dept) ;
for ( TBaseDept childId : childIds)
{
queryChildNodes ( childId. getId ( ) ) ;
ids. add ( childId. getId ( ) ) ;
}
ids. add ( id) ;
return ids;
}