25hibernate_training_tree

package com.bjsxt.hibernate;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class ExportToDB {

    /**
     * @param args
     
*/
    public static void main(String[] args) {

        // 读取配置文件
        Configuration cfg = new Configuration().configure();

        // 创建SchemaExport对象
        SchemaExport export = new SchemaExport(cfg);

        // 创建数据库表
        export.create(truetrue);

    }

}
---------------------------------------------------------------------------
package com.bjsxt.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {

    private static SessionFactory factory;

    static {
        Configuration cfg = new Configuration().configure();
        factory = cfg.buildSessionFactory();
    }

    public static SessionFactory getSessionFactory() {
        return factory;
    }

    public static Session getSession() {
        return factory.openSession();
    }

    public static void closeSession(Session session) {
        if (session != null) {
            if (session.isOpen()) {
                session.close();
            }
        }
    }
}
---------------------------------------------------------------------------
package com.bjsxt.hibernate;

import java.util.Set;

public class Node {//为了显示缩进

    
// 标识符
    private int id;

    // 节点名称
    private String name;

    // 层次
    private int level;

    // 是否叶子节点
    private boolean leaf;//考虑到效率,如果是叶子,我们就不用递归了

    
// 父节点 * --- 模拟1方
    private Node parent;

    // 子节点 1 --- *模拟多方
    private Set children;

    public Set getChildren() {
        return children;
    }

    public void setChildren(Set children) {
        this.children = children;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public boolean isLeaf() {
        return leaf;
    }

    public void setLeaf(boolean leaf) {
        this.leaf = leaf;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Node getParent() {
        return parent;
    }

    public void setParent(Node parent) {
        this.parent = parent;
    }
}

---------------------------------------------------------------------------
package com.bjsxt.hibernate;

import java.io.File;
import java.util.Iterator;
import java.util.Set;

import org.hibernate.Session;

public class NodeManager {

    private static NodeManager nodeManager;

    private NodeManager() {
    }
 
    public static synchronized NodeManager getInstance() {
        if (nodeManager == null) {
            nodeManager = new NodeManager();
        }

        return nodeManager;
    }

    // 创建树型结构
    public void createTree(String dir) {
        Session session = HibernateUtils.getSession();

        try {
            session.beginTransaction();

            File root = new File(dir);
            saveTree(root, session, null0);// 第一个Node的parent为null,所以每三个参数为null

            session.getTransaction().commit();
        } catch (RuntimeException e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        } finally {
            HibernateUtils.closeSession(session);
        }
    }

    // 递归创建一棵树
    private void saveTree(File file, Session session, Node parent, int level) {

        if (file == null || !file.exists()) {
            return;
        }

        boolean isLeaf = file.isFile();

        Node node = new Node();
        node.setName(file.getName());
        node.setLevel(level);
        node.setParent(parent);
        node.setLeaf(isLeaf);
        session.save(node);

        File[] subs = file.listFiles();
        if (subs != null && subs.length > 0) {
            for (int i = 0; i < subs.length; i++) {
                saveTree(subs[i], session, node, level + 1);
            }
        }
    }

    public void printTree(int id) {
        Session session = HibernateUtils.getSession();

        try {
            session.beginTransaction();

            Node root = (Node) session.load(Node.class, id);
            printNode(root);//从根节点开始,依次打印出所有的节点

            session.getTransaction().commit();
        } catch (RuntimeException 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);
        }
    }
}

---------------------------------------------------------------------------
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.bjsxt.hibernate.Node" table="t_node">
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="name"/>
        <property name="level"/>
        <property name="leaf"/>
        
        
        <!--自关联
        pid reforeign key (pid) references t_node (id)
        -->
        
        
        <many-to-one name="parent" column="pid"/>
        <set name="children" lazy="extra" inverse="true">
            <key column="pid"/>
            <one-to-many class="com.bjsxt.hibernate.Node"/>
        </set>
    </class>
</hibernate-mapping>

---------------------------------------------------------------------------
package com.bjsxt.hibernate;

import junit.framework.TestCase;

public class NodeManagerTest extends TestCase {

    public void testCreateTree() {
        //E:\workspaceforjee\25hibernate_training_tree
        NodeManager.getInstance().createTree("E:\\workspaceforjee\\25hibernate_training_tree\\");
    }
   
    public void testPrintTree() {
        NodeManager.getInstance().printTree(1);
    }

}

---------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration
    PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/25hibernate_training_tree</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        
        <!-- 
        <property name="hibernate.show_sql">true</property>
         -->
        <mapping resource="com/bjsxt/hibernate/Node.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

---------------------------------------------------------------------------
ExportDB:
create table t_node (id integer not null auto_increment, name varchar(255), level integer, leaf bit, pid integer, primary key (id))
alter table t_node add index FKCB608EED3F93ED7D (pid), add constraint FKCB608EED3F93ED7D foreign key (pid) references t_node (id)

mysql> create database 25hibernate_training_tree;
Query OK, 1 row affected (0.03 sec)

mysql> use 25hibernate_training_tree;
Database changed
mysql> show tables;
+-------------------------------------+
| Tables_in_25hibernate_training_tree |
+-------------------------------------+
| t_node                              |
+-------------------------------------+
1 row in set (0.00 sec)

mysql> select *  from t_node;
Empty set (0.00 sec)

mysql> desc t_node;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(255) | YES  |     | NULL    |                |
| level | int(11)      | YES  |     | NULL    |                |
| leaf  | bit(1)       | YES  |     | NULL    |                |
| pid   | int(11)      | YES  | MUL | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
5 rows in set (0.06 sec)

//NodeManager.getInstance().printTree(1);
25hibernate_training_tree[8]
  |--readme.txt
  |--.classpath
  |--src[3]
  |  |--com[1]
  |  |  |--bjsxt[1]
  |  |  |  |--hibernate[6]
  |  |  |  |  |--NodeManagerTest.java
  |  |  |  |  |--ExportToDB.java
  |  |  |  |  |--Node.hbm.xml
  |  |  |  |  |--NodeManager.java
  |  |  |  |  |--Node.java
  |  |  |  |  |--HibernateUtils.java
  |  |--log4j.properties
  |  |--hibernate.cfg.xml
  |--readme.doc
  |--~$readme.doc
  |--~WRL0004.tmp
  |--.project
  |--bin[3]
  |  |--hibernate.cfg.xml
  |  |--log4j.properties
  |  |--com[1]
  |  |  |--bjsxt[1]
  |  |  |  |--hibernate[6]
  |  |  |  |  |--Node.class
  |  |  |  |  |--HibernateUtils.class
  |  |  |  |  |--ExportToDB.class
  |  |  |  |  |--NodeManager.class
  |  |  |  |  |--Node.hbm.xml
  |  |  |  |  |--NodeManagerTest.class
  
  
  mysql> select *  from t_node;
+----+---------------------------+-------+------+------+
| id | name                      | level | leaf | pid  |
+----+---------------------------+-------+------+------+
|  1 | 25hibernate_training_tree |     0 |      | NULL |
|  2 | .classpath                |     1 |     |    1 |
|  3 | .project                  |     1 |     |    1 |
|  4 | bin                       |     1 |      |    1 |
|  5 | com                       |     2 |      |    4 |
|  6 | bjsxt                     |     3 |      |    5 |
|  7 | hibernate                 |     4 |      |    6 |
|  8 | ExportToDB.class          |     5 |     |    7 |
|  9 | HibernateUtils.class      |     5 |     |    7 |
10 | Node.class                |     5 |     |    7 |
11 | Node.hbm.xml              |     5 |     |    7 |
12 | NodeManager.class         |     5 |     |    7 |
13 | NodeManagerTest.class     |     5 |     |    7 |
14 | hibernate.cfg.xml         |     2 |     |    4 |
15 | log4j.properties          |     2 |     |    4 |
16 | readme.doc                |     1 |     |    1 |
17 | readme.txt                |     1 |     |    1 |
18 | src                       |     1 |      |    1 |
19 | com                       |     2 |      |   18 |
20 | bjsxt                     |     3 |      |   19 |
21 | hibernate                 |     4 |      |   20 |
22 | ExportToDB.java           |     5 |     |   21 |
23 | HibernateUtils.java       |     5 |     |   21 |
24 | Node.hbm.xml              |     5 |     |   21 |
25 | Node.java                 |     5 |     |   21 |
26 | NodeManager.java          |     5 |     |   21 |
27 | NodeManagerTest.java      |     5 |     |   21 |
28 | hibernate.cfg.xml         |     2 |     |   18 |
29 | log4j.properties          |     2 |     |   18 |
+----+---------------------------+-------+------+------+
29 rows in set (0.00 sec)
  
  //NodeManager.getInstance().printTree(4);
  |--bin[3]
  |  |--hibernate.cfg.xml
  |  |--com[1]
  |  |  |--bjsxt[1]
  |  |  |  |--hibernate[6]
  |  |  |  |  |--HibernateUtils.class
  |  |  |  |  |--ExportToDB.class
  |  |  |  |  |--NodeManager.class
  |  |  |  |  |--Node.hbm.xml
  |  |  |  |  |--NodeManagerTest.class
  |  |  |  |  |--Node.class
  |  |--log4j.properties  
  
原文地址:https://www.cnblogs.com/alamps/p/2629855.html