树状结构表设计

设计:

数据库中:表结构id pid name三个字段。

java程序中:设计一个类如下:

@Entity
public class Org {
    private int id;
    private String name;
    private Set<Org> children = new HashSet<Org>();
    private Org parent;
    
    @Id
    @GeneratedValue
    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;
    }
    @OneToMany(mappedBy="parent",cascade=CascadeType.ALL,fetch=FetchType.EAGER)    
    public Set<Org> getChildren() {
        return children;
    }
    public void setChildren(Set<Org> children) {
        this.children = children;
    }
    @ManyToOne
    public Org getParent() {
        return parent;
    }    
    public void setParent(Org parent) {
        this.parent = parent;
    }

}

对应的junit:

public class TestTree {
    private static SessionFactory sf;
    @Before
    public void beforeTest(){
        sf = new Configuration().configure().buildSessionFactory();
    }
    @After
    public void afterTest(){
        sf.close();
    }
    
    @Test
    public void testSave(){
        Org o = new Org();
        o.setName("总公司");
        Org o1 = new Org();
        o1.setName("分公司1");
        Org o2 = new Org();
        o2.setName("分公司2");
        Org o1_1 = new Org();
        o1_1.setName("分公司1_1");
        Org o1_2 = new Org();
        o1_2.setName("分公司1_2");        
        
        o.getChildren().add(o1);
        o.getChildren().add(o2);
        o1.getChildren().add(o1_1);
        o1.getChildren().add(o1_2);
        
        o1.setParent(o);
        o2.setParent(o);
        o1_1.setParent(o1);
        o1_2.setParent(o1);
            
        Session s = sf.getCurrentSession();
        s.beginTransaction();
        s.save(o);
        s.getTransaction().commit();
    }
    
    @Test
    public void testLoad(){
        Session s = sf.getCurrentSession();
        s.beginTransaction();
        Org o = (Org)s.load(Org.class,1);
        print(o,0);        
        s.getTransaction().commit();
    }
    private void print(Org o,int level) {
//        if(o==null){
//            return;
//        }
        StringBuffer sb = new StringBuffer();
        for(int i=0; i<level; i++){
            sb.append("----");
        }
        System.out.println(sb+o.getName());
        for(Org child: o.getChildren()){
            print(child,level+1);
        }        
    }    
}

 

posted @ 2014-07-30 13:06  seven7seven  阅读(528)  评论(0编辑  收藏  举报