📄 treedemo.java
字号:
package tutorial.dev.tree;import java.io.Serializable;import java.sql.Connection;import java.util.HashSet;import java.util.Iterator;import java.util.Set;import net.sf.hibernate.HibernateException;import net.sf.hibernate.Session;import net.sf.hibernate.SessionFactory;import net.sf.hibernate.Transaction;import net.sf.hibernate.cfg.Configuration;public class TreeDemo { public static void main(String[] args) { try { new TreeDemo(); } catch(HibernateException he) { he.printStackTrace(); } } public TreeDemo() throws HibernateException { Configuration config = new Configuration(); // add the classes you want to persist // make sure the mapping files are on the classpath config.addClass(Friend.class); SessionFactory sf = config.buildSessionFactory(); Session sess = sf.openSession(); Transaction tx = null; Connection con = null; // store the orderlist and all products Serializable id = null; Friend a = new Friend("a"); Friend b = new Friend("b"); Friend c = new Friend("c"); Friend d = new Friend("d"); Friend e = new Friend("e"); Friend f = new Friend("f"); Friend g = new Friend("g"); Friend h = new Friend("h"); a.getFriends().add(b); a.getFriends().add(c); b.getFriends().add(d); b.getFriends().add(e); b.getFriends().add(f); d.getFriends().add(g); d.getFriends().add(h); e.getFriends().add(h); c.getFriends().add(f); a = new Friend("Root"); makeFriends(a); try { tx = sess.beginTransaction(); sess.save(a); tx.commit(); } catch (HibernateException he) { if (tx!=null) tx.rollback(); throw he; } finally { sess.close(); } Set friends = new HashSet(); sess = sf.openSession(); try { tx = sess.beginTransaction(); Friend root = (Friend)sess.get(Friend.class, a.getId()); friends(root, friends, 2); tx.commit(); } catch (HibernateException he) { if (tx!=null) tx.rollback(); throw he; } finally { sess.close(); } for (Iterator iter = friends.iterator(); iter.hasNext();) { Friend friend = (Friend) iter.next(); System.out.println("Friend: " + friend.getName()); } System.out.println("FriendCount: " + friends.size()); } protected void friends(Friend root, Set friends, int distance) { if (distance > 0) { friends.addAll(root.getFriends()); for (Iterator iter = root.getFriends().iterator(); iter.hasNext();) { Friend friend = (Friend) iter.next(); friends(friend, friends, distance -1); } } } private int level = 0; private int count = 0; protected void makeFriends(Friend root) { System.out.println("Level: " + level + " -> " + count); if (level < 3) { for(int i = 0; i < 10; i++) { if (Math.random() < 0.6) { Friend f = new Friend(root.getName() +"/"+ i); count++; root.getFriends().add(f); level++; makeFriends(f); level--; } } } else { } } }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -