首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

hibernate annotation树状结构的投射

2012-10-24 
hibernate annotation树状结构的映射表结构如下:/** * 组织机构树 * @author zhibinli */@Entitypublic cl

hibernate annotation树状结构的映射
表结构如下:
/** * 组织机构树 * @author zhibinli */@Entitypublic class Org { private int id; private String name; private Set<Org> chileren = new HashSet<Org>();//一对多 private Org org;//多对一 双向映射 @OneToMany(mappedBy="org",cascade=CascadeType.ALL,fetch=FetchType.EAGER) public Set<Org> getChileren() { return chileren; } public void setChileren(Set<Org> chileren) { this.chileren = chileren; } @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } @Column public String getName() { return name; } public void setName(String name) { this.name = name; } @ManyToOne @JoinColumn(name="pid") public Org getOrg() { return org; } public void setOrg(Org org) { this.org = org; }}

这里存在一个双向的一对多或者说多对一,对于父节点来说,它与子节点是一对多的关系,对于子节点来说,它与父节点是多对一的关系。即在同一个类里一对多与多对一构成双向映射。
测试例子如下:

public class HibernateTest {    private static SessionFactory sf = null;    @BeforeClass    public static void beforeClass() {        sf = new AnnotationConfiguration().configure().buildSessionFactory();    }    @Test     public void testSave() throws Exception {        Session s = sf.getCurrentSession();        org.hibernate.Transaction t = s.beginTransaction();        Student student = new Student();        student.setName("lzb");        Org o = new Org();        o.setName("总公司");        Org o1 = new Org();        Org o2 = new Org();        Org o11 = new Org();        Org o21 = new Org();        o1.setName("分公司1");        o2.setName("分公司2");        o11.setName("分公司1下分公司1");        o21.setName("分公司2下分公司1");        //设置双方关系        o.getChileren().add(o1);        o.getChileren().add(o2);        o1.setOrg(o);        o2.setOrg(o);        o1.getChileren().add(o11);        o11.setOrg(o1);        o2.getChileren().add(o21);        o21.setOrg(o2);        s.save(o);        t.commit();    }    @Test    public void testLoad() throws Exception {        Session s = sf.getCurrentSession();        Transaction t = s.beginTransaction();        Org o = (Org)s.load(Org.class, 1);        printOrg(o,0);        t.commit();    }    /**     * 典型的递归打印树     * @param o 节点     * @param level 节点层次     * @throws java.lang.Exception     */    public void printOrg(Org o,int level) throws Exception {        String s = "";        for(int i=0;i<level;i++) {            s+="----";        }        System.out.println(s+o.getName());        Set<Org> children = o.getChileren();                for(Org temp : children) {            printOrg(temp,level+1);        }            }     @AfterClass     public static void afterClass() {         sf.close();     }}

热点排行