026 hibernate操作樹形結構

來源:互聯網
上載者:User

標籤:style   io   color   ar   os   使用   java   sp   for   

樹形結構:也就是目錄結構,有父目錄、子目錄、檔案等資訊,而在程式中樹形結構只是稱為節點。

         一棵樹有一個根節點,而根節點也有一個或多個子節點,而一個子節點有且僅有一個父節點(當前除根節點外),而且也存在一個或多個子節點。

         也就是說樹形結構,重點就是節點,也就是我們需要關心的節點對象。

         節點:一個節點有一個ID、一個名稱、它所屬的父節點(根節點無父節點或為null),有一個或多的子節點等其它資訊。

Hibernate將節點抽取出成實體類,節點相對於父節點是“多對一”映射關係,節點相對於子節點是“一對多”映射關係。  

節點實體類:

/** * 節點*/

public class Node {

    private int id; //標識符

    private String name; //節點名稱 

    private int level; //層次,為了輸出設計   

    private boolean leaf; //是否為葉子節點,這是為了效率設計,可有可無

    //父節點:因為多個節點屬於一個父節點,因此用hibernate映射關係說是“多對一”

    private Node parent;

    //子節點:因為一個節點有多個子節點,因此用hibernate映射關係說是“一對多”

    private Set children;

 

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id = id;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public int getLevel() {

        return level;

    }

    public void setLevel(int level) {

        this.level = level;

    }

    public boolean isLeaf() {

        return leaf;

    }

    public void setLeaf(boolean leaf) {

        this.leaf = leaf;

    }

    public Node getParent() {

        return parent;

    }

    public void setParent(Node parent) {

        this.parent = parent;

    }

    public Set getChildren() {

        return children;

    }

    public void setChildren(Set children) {

        this.children = children;

    }

}

 

節點對應檔:

<hibernate-mapping>

    <class name="com.wjt276.hibernate.Node" table="t_node">

        <id name="id" column="id">

            <generator class="native"/>

        </id>

        <property name="name"/>

        <property name="level"/>

        <property name="leaf"/>

<!— 一對多:加入一個外鍵,參照當前表t_node主鍵

    而屬性parent類型為Node,也就是當前類,則會在同一個表中加入這個欄位,參照這個表的主鍵-->

        <many-to-one name="parent" column="pid"/>

    <!-- <set>標籤是映射一對多的方式,加入一個外鍵,參照主鍵。-->

        <set name="children" lazy="extra" inverse="true">

            <key column="pid"/>

            <one-to-many class="com.wjt276.hibernate.Node"/>

        </set>

       

    </class>

</hibernate-mapping>

測試代碼:

 

public class NodeTest extends TestCase {

    //測試節點的存在

    public void testSave1(){

        NodeManage.getInstanse().createNode("F:\\JAVA\\JavaProject\\hibernate\\hibernate_training_tree");

    }

   

    //測試節點的載入

    public void testPrintById(){

        NodeManage.getInstanse().printNodeById(1);

    }

}

 

相應的類代碼:

public class NodeManage {

   

    private static NodeManage nodeManage= new NodeManage();

   

    private NodeManage(){}//因為要使用單例,所以將其構造方法私人化

   

    //向外提供一個介面

    public static NodeManage getInstanse(){

        return nodeManage;

    }

 

    /**

     * 建立樹

     * @param filePath 需要建立樹目錄的根目錄

     */

    public void createNode(String dir) {

        Session session = null;

       

        try {

            session = HibernateUtils.getSession();

            session.beginTransaction();

           

            File root = new File(dir);

            //因為第一個節點無父節點,因為是null

            this.saveNode(root, session, null, 0);

           

            session.getTransaction().commit();

        } catch (HibernateException e) {

            e.printStackTrace();

            session.getTransaction().rollback();

        } finally {

            HibernateUtils.closeSession(session);

        }

    }

 

    /**

     * 儲存節點對象至資料庫

     * @param file 節點所對應的檔案

     * @param session session

     * @param parent 父節點

     * @param level 層級

     */

    public void saveNode(File file, Session session, Node parent, int level) {

       

        if (file == null || !file.exists()){

            return;

        }

       

        //如果是檔案則返回true,則表示是葉子節點,否則為目錄,非葉子節點

        boolean isLeaf = file.isFile();

       

        Node node = new Node();

        node.setName(file.getName());

        node.setLeaf(isLeaf);

        node.setLevel(level);

        node.setParent(parent);

       

        session.save(node);

       

        //進行迴圈迭代子目錄

        File[] subFiles = file.listFiles();

        if (subFiles != null && subFiles.length > 0){

            for (int i = 0; i < subFiles.length ; i++){

                this.saveNode(subFiles[i], session, node, level + 1);

            }

        }

    }

 

    /**

     * 輸出樹結構

     * @param id

     */

    public void printNodeById(int id) {

 

        Session session = null;

       

        try {

            session = HibernateUtils.getSession();

            session.beginTransaction();

           

            Node node = (Node)session.get(Node.class, 1);

           

            printNode(node);

           

            session.getTransaction().commit();

        } catch (HibernateException e) {

            e.printStackTrace();

            session.getTransaction().rollback();

        } finally {

            HibernateUtils.closeSession(session);

        }      

    }

 

   

    private void printNode(Node node) {

       

        if (node == null){

            return;

        }

       

        int level = node.getLevel();

       

        if (level > 0){

            for (int i = 0; i < level; i++){

                System.out.print("  |");

            }

            System.out.print("--");            

        }

        System.out.println(node.getName() + (node.isLeaf() ? "" : "[" + node.getChildren().size() + "]"));

       

        Set children = node.getChildren();

        for (Iterator iter = children.iterator(); iter.hasNext(); ){

            Node child = (Node)iter.next();

            printNode(child);

        }

    }

}

 

026 hibernate操作樹形結構

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.