Everything is code......
首先是位于src下的Hibernate核心配置文件
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/jadyer?characterEncoding=UTF-8</property>
<property name="connection.username">root</property>
<property name="connection.password">hongyu</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 不要输出SQL语句,否则会影响树形结构的打印效果 -->
<!--
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
-->
<mapping resource="com/jadyer/hibernate/Node.hbm.xml" />
</session-factory>
</hibernate-configuration>
然后是用到的实体类映射文件Node.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!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.jadyer.hibernate.Node" table="t_node">
<id name="id">
<generator class="native" />
</id>
<property name="name" />
<property name="level" />
<property name="leaf" />
<many-to-one name="parent" column="pid" />
<set name="children" lazy="extra" inverse="true">
<key column="pid" />
<one-to-many class="com.jadyer.hibernate.Node" />
</set>
</class>
</hibernate-mapping>
接下来就是实体类Node.java
package com.jadyer.hibernate;
import java.util.Set;
public class Node {
private int id; // 标识符
private String name; // 节点名称
private int level; // 层次
private boolean leaf; // 是否是叶子节点
private Node parent; // 父节点 * --- 1
private Set<Node> children; // 子节点 1 --- *
/*--六个属性对应的setter和getter略--*/
}
然后是利用Hibernate映射文件生成Table的Java类
package com.jadyer.hibernate;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
/**
* 利用Hibernate映射文件生成数据表
*/
public class ExportDB {
public static void main(String[] args) {
// 读取hibernate.cfg.xml文件
Configuration cfg = new Configuration().configure();
// 创建SchemaExport对象
SchemaExport export = new SchemaExport(cfg);
// 创建数据库表
export.create(true, true);
}
}
下面是自定义的用于生成Session的工具类
package com.jadyer.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateSessionUtils {
private static SessionFactory factory;
static {
Configuration cfg = new Configuration().configure();
factory = cfg.buildSessionFactory();
}
public static Session getSession() {
return factory.openSession();
}
public static void closeSession(Session session) {
if (null != session && session.isOpen()) {
session.close();
}
}
}
下面就是核心的节点处理类NodeManager.java
package com.jadyer.hibernate;
import java.io.File;
import java.util.Set;
import org.hibernate.Session;
/**
* 节点处理类
* @see 这里用到了递归
*/
public class NodeManager {
private static NodeManager nodeManager;
private NodeManager() {}
public static synchronized NodeManager getInstance() {
if (null == nodeManager) {
nodeManager = new NodeManager();
}
return nodeManager;
}
/**
* 创建树型结构
*/
public void createTree(String dir) {
Session session = HibernateSessionUtils.getSession();
try {
session.beginTransaction();
File root = new File(dir);
saveTree(root, session, null, 0);
session.getTransaction().commit();
} catch (RuntimeException e) {
e.printStackTrace();
session.getTransaction().rollback();
} finally {
HibernateSessionUtils.closeSession(session);
}
}
private void saveTree(File file, Session session, Node parent, int level) {
if (null == file || !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 (null != subs && 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 = HibernateSessionUtils.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 {
HibernateSessionUtils.closeSession(session);
}
}
private void printNode(Node node) {
if (null == node) {
return;
}
int level = node.getLevel();
if (0 < level) {
for (int i = 0; i < level; i++) {
System.out.print(" |");
}
System.out.print("--");
}
System.out.println(node.getName() + (node.isLeaf() ? "" : "[" + node.getChildren().size() + "]"));
Set<Node> children = node.getChildren();
for (Node child : children) {
printNode(child);
}
}
}
最后是借助JUnit3.8实现的单元测试类
package com.jadyer.hibernate;
import com.jadyer.hibernate.NodeManager;
import junit.framework.TestCase;
/**
* 树形结构测试类
* @see 测试时需要利用JUnit进行单元测试
* @see 首先执行ExportDB.main()方法
* @see 然后执行testCreateTree()方法
* @see 最后执行testPrintTree()方法
*/
public class NodeManagerTest extends TestCase {
/**
* 递归读取相应目录,并把它存放到数据库表中
* 该方法用来为testPrintTree()的执行准备数据
*/
public void testCreateTree() {
NodeManager.getInstance().createTree("E://Develop//MyWorkspace//hibernate_tree//");
}
/**
* 输出节点为 1 的节点,其实就是根节点
*/
public void testPrintTree() {
NodeManager.getInstance().printTree(1);
}
}
下面就是在控制台上打印输出的结果
hibernate_tree[4]
|--src[2]
| |--hibernate.cfg.xml
| |--com[1]
| | |--jadyer[1]
| | | |--hibernate[6]
| | | | |--HibernateSessionUtils.java
| | | | |--Node.java
| | | | |--Node.hbm.xml
| | | | |--NodeManagerTest.java
| | | | |--NodeManager.java
| | | | |--ExportDB.java
|--.classpath
|--.project
|--bin[2]
| |--hibernate.cfg.xml
| |--com[1]
| | |--jadyer[1]
| | | |--hibernate[6]
| | | | |--HibernateSessionUtils.class
| | | | |--NodeManagerTest.class
| | | | |--Node.class
| | | | |--Node.hbm.xml
| | | | |--NodeManager.class
| | | | |--ExportDB.class