使用樹形結構保存實體

tree
閱讀原文請訪問個人博客 BrightLoong's Blog

以前在項目須要實現一個功能——將xml文件映射成實體,而後對映射的實體進行邏輯處理,最後保存到數據庫中;因爲xml結構的數據是結構化的數據,因此須要保證保存的數據具備正確的主外鍵關聯。以下所示,是一個須要保存到數據庫的xml文件。當映射成對應的實體school和student的時候,咱們須要知道「school-one」下面有哪些學生,「school-two」下面有哪些學生,這個時候想到了使用樹形結構來保存實體,讓實體之間依然存在關聯關係。java

<school-inf>
  <msg>2017-10-1XX省學校信息總彙</msg>
  <schools>
    <school>
      <name>school-one</name>
      <students>
        <student>Jack</student>
        <student>Rose</student>
        <student>Jon</student>
      </students>
    </school>
    <school>
      <name>school-two</name>
      <students>
        <student>Bob</student>
        <student>Alisa</student>
        </students>
      </school>
    </schools>
</school-inf>
複製代碼

樹形工具

如下是樹形工具類的實現,包含了樹形節點類和樹形結構類,因爲代碼中註釋已經比較全面,因此不作過多的說明。node

樹形節點類BeanTreeNode.java

每個節點對應一個實體,節點包含了實體信息,爲了保證明體之間的關聯關係,須要留有父節點信息,全部的子節點信息。由此推斷出,節點的主要成員有git

  • 父節點信息
  • 全部子節點信息
  • 當前實體信息

爲了方便操做,我還多增長了id和pid(parent id),以及節點類型(nodeType)。對id的相關操做我並無添加,若是須要能夠自行添加。github

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/** * 實體樹形結構點 * BeanTreeNode * @author BrightLoong * @version 1.0 * */
public class BeanTreeNode {
    
    /**標識id*/
    private String id;
    
    /**父id標識,爲了方便獲取冗餘出來*/
    private String pid;
    
    /**父節點*/
    private BeanTreeNode parentNode;
    
    /**節點類型*/
    private String nodeType;
    
    /**節點值*/
    private Object bean;
    
    /**子節點*/
    private List<BeanTreeNode> childNodes;
    

    /** * @param parentNode * @param nodeType * @param bean * @param childNodes */
    public BeanTreeNode(BeanTreeNode parentNode, String nodeType, Object bean) {
        this.parentNode = parentNode;
        this.nodeType = nodeType;
        this.bean = bean;
        this.childNodes = new ArrayList<BeanTreeNode>();
        this.id = UUID.randomUUID().toString().replaceAll("-", "");
        if (parentNode != null) {
            this.pid = parentNode.getId();
        }
    }

    /** * @return the nodeType */
    public String getNodeType() {
        return nodeType;
    }

    /** * @param nodeType the nodeType to set */
    public void setNodeType(String nodeType) {
        this.nodeType = nodeType;
    }

    /** * @return the parentNode */
    public BeanTreeNode getParentNode() {
        return parentNode;
    }

    /** * @param parentNode the parentNode to set */
    public void setParentNode(BeanTreeNode parentNode) {
        this.parentNode = parentNode;
    }

    /** * @return the bean */
    public Object getBean() {
        return bean;
    }

    /** * @param bean the bean to set */
    public void setBean(Object bean) {
        this.bean = bean;
    }

    /** * @return the childNodes */
    public List<BeanTreeNode> getChildNodes() {
        return childNodes;
    }

    /** * @param childNodes the childNodes to set */
    public void setChildNodes(List<BeanTreeNode> childNodes) {
        this.childNodes = childNodes;
    }

    /** * @return the id */
    public String getId() {
        return id;
    }

    /** * @param id the id to set */
    public void setId(String id) {
        this.id = id;
    }

    /** * @return the pid */
    public String getPid() {
        return pid;
    }

    /** * @param pid the pid to set */
    public void setPid(String pid) {
        this.pid = pid;
    }
    
    /** * 是否具備子節點 * @return true or false */
    public boolean haveChild() {
        return !CollectionUtils.isEmpty(childNodes);
    }
}
複製代碼

樹形結構類BeanTree.java

BeanTree.java裏面包含了以下的一些經常使用操做:數據庫

  • 返回根節點
  • 返回最後添加節點
  • 判斷是否具備子節點
  • 添加節點
  • 移動節點到其餘節點下
  • 獲取對應nodeType的全部節點或實體
  • 根據實體獲取節點
  • 獲取父節點
  • 轉化爲map結構

代碼以下apache

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;

/** * 實體樹形結構 * BeanTree * @author BrightLoong * @version 1.0 * */
public class BeanTree {
    /**根節點*/
    private BeanTreeNode root;
    
    /** * 最新添加的節點 */
    private BeanTreeNode currentNode;
    
    
    /** * @return the currentNode */
    public BeanTreeNode getCurrentNode() {
        return currentNode;
    }

    /** * @return the root */
    public BeanTreeNode getRoot() {
        return root;
    }
    
    /** * 判斷節點是否有子節點. * @param node 要判斷的節點 * @return true or false */
    public boolean haveChild(BeanTreeNode node) {
        return CollectionUtils.isEmpty(node.getChildNodes());
    }
    
    /** * 在父節點上面添加節點,並返回天添加的節點. * @param parentNode 父節點 * @param bean 要添加的bean * @param nodeType 節點類型 * @return 返回包含bean的節點 */
    public BeanTreeNode addNode(BeanTreeNode parentNode, Object bean, String nodeType) {
        BeanTreeNode node;
        if (bean == null) {
            return null;
        }
        //若是沒有父節點說明爲root根節點
        if (parentNode == null) {
            node = root = new BeanTreeNode(null, nodeType, bean);
        } else {
            //建立子節點,並添加到父節點上
            node = new BeanTreeNode(parentNode, nodeType, bean);
            parentNode.getChildNodes().add(node);
        }
        currentNode = node;
        return node;
    }
    
    /** * 將當期bean-sBean,以及sBean下的子Bean,掛到dBean下 * @param sBean 源Bean * @param dBean 目的父Bean */
    public void removeTo(Object sBean, Object dBean) {
        BeanTreeNode sNode = getNodeByBean(sBean);
        BeanTreeNode dNode = getNodeByBean(dBean);
        removeTo(sNode, dNode);
    }
    
    /** * 將當期node-sNode,以及sNode下的子Node,掛到dNode下 * @param sNode 源node * @param dNode 目的父node */
    public void removeTo(BeanTreeNode sNode, BeanTreeNode dNode) {
        //從當前父節點移除sNode
        sNode.getParentNode().getChildNodes().remove(sNode);
        //將sNode移到dNode下
        dNode.getChildNodes().add(sNode);
        //修改sNode的父Id和父節點
        sNode.setPid(dNode.getId());
        sNode.setParentNode(dNode);
    }
    
    /** * 獲取父bean. * @param bean 子bean * @return 返回父bean */
    public Object getParentBean(Object bean) {
        return getNodeByBean(bean).getParentNode().getBean();
    }
    
    /** * 根據傳入的bean獲取bean下面對應類型的子bean. * @param bean 當前bean * @param nodeType 節點類型 * @return 子bean的集合 */
    public List<Object> getBeanListByBeanAndNodeType(Object bean, String nodeType) {
        BeanTreeNode node = getNodeByBean(bean);
        return getBeanListByNodeType(node, nodeType);
    }
    
    /** * 根據傳入的bean獲取包含bean的Node節點 * @param node 當前node * @param bean 要查找的bean * @return node節點 */
    public BeanTreeNode getNodeByBean(BeanTreeNode node, Object bean) {
        BeanTreeNode resultNode = null;
        if (node.getBean().equals(bean)) {
            resultNode = node;
            return resultNode;
        } else {
            for (BeanTreeNode tempNode : node.getChildNodes()) {
                resultNode = getNodeByBean(tempNode, bean);
                if (resultNode != null) {
                    break;
                }
            }
        }
        return resultNode;
    }
    
    /** * 根據傳入的bean獲取root節點下包含bean的Node節點 * @param bean 要查找的bean * @return node節點 */
    public BeanTreeNode getNodeByBean(Object bean) {
        return getNodeByBean(root, bean);
    }
    
    /** * 根據節點類型返回當前節點下對應節點類型的bean的list集合. * 默認若是當前節點知足類型,那麼當前節點不會存在相同類型的子節點 * @param node 當前節點 * @param nodeType 節點類型 * @return */
    @SuppressWarnings("unchecked")
    public <T> List<T> getBeanListByNodeType(BeanTreeNode node, String nodeType) {
        List<T> beanList = new ArrayList<T>();
        if (node.getNodeType().equals(nodeType)) {
            beanList.add((T)node.getBean());
        } else {
            for (BeanTreeNode tempNode : node.getChildNodes()) {
                beanList.addAll((Collection<? extends T>) getBeanListByNodeType(tempNode, nodeType));
            }
        }
        return beanList;
    }
    /** * 根據節點類型返回根節點下對應節點類型的bean的list集合. * @param nodeType 節點類型 * @return */
    public <T> List<T> getBeanListByNodeType(String nodeType) {
        return getBeanListByNodeType(root, nodeType);
    }
    
    /** * 從root節點開始獲取對應nodeType的node. * @param nodeType 節點類型 * @return nodeType類型的節點集合 */
    public List<BeanTreeNode> getNodeListByNodeType(String nodeType) {
        return getNodeListByNodeType(root, nodeType);
    }
    
    /** * 從node節點開始獲取對應nodeType的node. * @param node node節點 * @param nodeType 節點類型 * @return nodeType類型的節點集合 */
    public List<BeanTreeNode> getNodeListByNodeType(BeanTreeNode node, String nodeType) {
        List<BeanTreeNode> nodeList = new ArrayList<BeanTreeNode>();
        if(node==null){
            return nodeList;  
        }
        if (nodeType.equals(node.getNodeType())) {
            nodeList.add(node);
        } else {
            for (BeanTreeNode tempNode : node.getChildNodes()) {
                nodeList.addAll(getNodeListByNodeType(tempNode, nodeType));  
            }
        }
        
        return nodeList;
    }
    
    /** * 將樹形結構轉化爲map. * @return */
    public Map<String, List<Object>> toMap() {
        return toMap(root);
    }
    
    /** * 將對應節點及其子節點轉化爲map. * @param node 樹節點 * @return 轉化後的map */
    public Map<String, List<Object>> toMap(BeanTreeNode node) {
        Map<String, List<Object>> map = new HashMap<String, List<Object>>();
        toMap(node, map);
        return map;
    }
    
    
    /** * 根據傳入的nodeType刪除對應的節點以及其全部子節點. * @param nodeType */
    public void delNodeByNodeType(String nodeType) {
        delNodeByNodeType(root, nodeType);
    }
    
    /** * 刪除node節點下,類型爲nodeType的節點和全部子節點 * @param node * @param nodeType */
    public void delNodeByNodeType(BeanTreeNode node, String nodeType) {
        List<BeanTreeNode> nodeList = getNodeListByNodeType(node, nodeType);
        for (BeanTreeNode beanTreeNode : nodeList) {
            beanTreeNode.getParentNode().getChildNodes().remove(beanTreeNode);
        }
    }
    
    /** * 從樹結構裏面刪除bean和相關node. * @param bean bean */
    public void delNodeByBean(Object bean) {
        BeanTreeNode node = getNodeByBean(bean);
        BeanTreeNode parentNode = node.getParentNode();
        List<BeanTreeNode> childNodes = parentNode.getChildNodes();
        Iterator<BeanTreeNode> it = childNodes.iterator();
        while (it.hasNext()) {
            BeanTreeNode beanTreeNode = it.next();
            if (node == beanTreeNode) {
                it.remove();
            }
        }
    }
    
    
    /** * 根據class返回對應的beanList. * @param cls class * @return beanList */
    public <T> List<Object> getBeanListByClass(Class<T> cls) {
        return getBeanListByClass(root, cls);
    }
    
    /** * 根據class返回對應的beanList. * @param node 節點 * @param cls class * @return beanList */
    public <T> List<Object> getBeanListByClass(BeanTreeNode node, Class<T> cls) {
        List<Object> beanList = new ArrayList<Object>();
        Object bean = node.getBean();
        if (cls.isAssignableFrom(bean.getClass())) {
            beanList.add(bean);
        }
        List<BeanTreeNode> childNodes = node.getChildNodes();
        for (BeanTreeNode beanTreeNode : childNodes) {
            beanList.addAll(getBeanListByClass(beanTreeNode, cls));
        }
        return beanList;
    }
    
    
    /** * 將對應節點及其子節點轉化爲map. * @param node 樹節點 * @param map 用來保存結果的map */
    private void toMap(BeanTreeNode node, Map<String, List<Object>> map) {
        String key = node.getNodeType();
        Object bean = node.getBean();
        if (map.containsKey(key)) {
            map.get(key).add(bean);
        } else {
            List<Object> list = new ArrayList<Object>();
            list.add(bean);
            map.put(key, list);
        }
        for (BeanTreeNode tempNode : node.getChildNodes()) {
            toMap(tempNode, map);
        }
    }
}
複製代碼

測試樹形工具

使用上面的xml進行測試,這裏就再也不作xml映射,假設存在上面xml所示的全部實體,「school-one」和「school-two」以及5個student,看看可否構造出想要的結構,測試類代碼以下。dom

class SchoolInf {
    private String msg;
    public SchoolInf(String msg) {
        this.msg = msg;
    }
}

class Student {
    private String name;
    public Student(String name) {
        this.name = name;
    }
}

class School {
    private String name;
    public School(String name) {
        this.name = name;
    }
}

public class Test {
    public static void main(String[] args) {
        SchoolInf schoolInf = new SchoolInf("2017-10-1XX省學校信息總彙");
        School school_one = new School("school-one");
        School school_two = new School("school-two");
        Student Jack = new Student("Jack");
        Student Rose = new Student("Rose");
        Student Jon = new Student("Jon");
        Student Bob = new Student("Bob");
        Student Alisa = new Student("Alisa");
        
        BeanTree tree = new BeanTree();
        BeanTreeNode root = tree.addNode(null, schoolInf, "root");
        BeanTreeNode school_node1 = tree.addNode(root, school_one, "school");
        BeanTreeNode school_node2 = tree.addNode(root, school_two, "school");
        tree.addNode(school_node1, Jack, "root");
        tree.addNode(school_node1, Rose, "root");
        tree.addNode(school_node1, Jon, "root");
        tree.addNode(school_node2, Bob, "root");
        tree.addNode(school_node2, Alisa, "root");
        
        System.out.println("end");
    }
}

複製代碼

咱們經過調試觀察樹結構變量「tree」的值以下:工具

result

能夠看出來可以構造出正確的結構,BeanTree中其餘的一些方法這裏就不在一一測試了。測試

更新記錄

  • 2018/1/10,在BeanTree中添加更多的操做方法。
相關文章
相關標籤/搜索