SoFunction
Updated on 2025-04-05

How to recursively delete any node of tree data

Java implements recursively deletion of any node of tree data

3 points to pay attention to

  1. The deleted node contains child nodes, delete child nodes and other child nodes
  2. The deleted node does not contain child nodes, and the parent node becomes a leaf node
  3. These two things are included in the same transaction and have atomicity

Implementation method

  1. Recursively traverse nodes and their children
  2. Atomicity, create a method, start a transaction,

General manual method of opening transactions

Connection connection = JDBCUtil_C3P0.getConnection();

try {
//Close transaction automatic commit (open transaction)(false);
//...Your operation//All the above operations will be submitted without exceptions.();
} catch (SQLException e) {
	// Once an exception occurs in a transaction, the transaction will be rolled back	();
	();
}finally{
	//Close the link resource	//...
}

The backend uses recursively to delete all children of the tree structure

controller

    /**
      * Delete tree nodes according to id
      *
      * @param id The id of the node to be deleted
      * @return true/false
      */
    @RequestMapping("/deleteTreeNodeById")
    public ResponseData<Boolean> deleteTreeNodeById(@RequestParam(name = "id") String id) {
        return successWithData((id));
    }

Service interface

boolean deleteTreeNodeById(String id);

Service interface implementation class

    @Override
    public boolean deleteTreeNodeById(String id) {
        List<String> deleteIdList = new LinkedList<>();
        (id);
        getAllChildrenIdList(id, deleteIdList);
        return (deleteIdList) == 1;
    }

    /**
      * Recursively query the list of all child nodes in the current node
      *
      * @param id
      * @param deleteIdList
      */
    private void getAllChildrenIdList(String id, List<String> deleteIdList) {
        QueryWrapper<ConfigDict> queryWrapper = new QueryWrapper<>();
        (ConfigDict.PARENT_ID, id);
        List<ConfigDict> childrenList = (queryWrapper);
        if ((childrenList)) {
            for (ConfigDict children : childrenList) {
                (());
                getAllChildrenIdList((), deleteIdList);
            }
        }
    }

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.