学习Hibernate生成目录树

xiaoxiao2026-09-10  21

<?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"/> <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> 在一个表中自身映射,使用一个pid列。多个子节点对应一个父节点(parent),一个父节点对应多个子节点,使用set映射,inverse=true,翻转,在多的一端管理。 NodeManager类: package cn.com.hibernate;import java.io.File;import java.util.Iterator;import java.util.Set;import org.hibernate.Session;import org.hibernate.Transaction;public class NodeManager { private static NodeManager nodeManager= null; public NodeManager(){ } public static synchronized NodeManager getInstance(){ if(nodeManager==null){ nodeManager = new NodeManager(); } return nodeManager; } public void createTree(String dir){ Session session = HibernateUtil.getSession(); Transaction tx = session.beginTransaction(); try{ File file = new File(dir); saveTree(file,session,null,0); tx.commit(); }catch(Exception ex){ ex.printStackTrace(); tx.rollback(); }finally{ HibernateUtil.closeSession(session); } } public 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.setLeaf(isLeaf); node.setParent(parent); node.setLevel(level); session.save(node); File[] subFile = file.listFiles(); if(subFile!=null && subFile.length!=0){ for(int i=0;i<subFile.length;i++){ saveTree(subFile[i],session,node,level+1); } } } public void printTree(int id){ Session session = HibernateUtil.getSession(); Transaction tx = session.beginTransaction(); try{ Node root = (Node)session.load(Node.class, 1); printNode(root); tx.commit(); }catch(Exception ex){ ex.printStackTrace(); tx.rollback(); }finally{ HibernateUtil.closeSession(session); } } public void printNode(Node root){ if(root==null){ return; } int level = root.getLevel(); if(level>0){ for(int i=0;i<level;i++){ System.out.print(" |"); } System.out.print("--"); } System.out.println(root.getName()+(root.isLeaf()?"":"["+root.getChildren().size()+"]")); Set<Node> children = root.getChildren(); for(Iterator<Node> iter = children.iterator();iter.hasNext();){ Node node = iter.next(); printNode(node); } }} 主要是树的生成和树的遍历。 Test类: package cn.com.hibernate;import junit.framework.TestCase;public class createTreeTest extends TestCase { public void testCreateTree(){ NodeManager.getInstance().createTree("D:\\Myeclipse6.5workspace\\Hibernate_tree\\"); } public void testPrintTree(){ NodeManager.getInstance().printTree(1); }}
转载请注明原文地址: https://www.6miu.com/read-5052488.html

最新回复(0)