資料庫模型(id-pid):一個父親有多個孩子,而一個孩子只有一個父親,這樣的結構就是一顆樹。在資料庫表中,設計的是id和pid(parent_id)。通過id和pid就存放一顆樹了。
從物件導向的設計角度出發,在樹的節點類中不宜放pid,一個節點有1個或者0個父親,而有0個或者孩子。因此設計如下:這是一個組織機構,每個機構有父機構和子機構。
package com.xie.hibernate.modal;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
@Entity
public class Org {
private int id;
private String name;
private Set<Org> childrenOrgs=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> getChildrenOrgs() {
return childrenOrgs;
}
public void setChildrenOrgs(Set<Org> childrenOrgs) {
this.childrenOrgs = childrenOrgs;
}
@ManyToOne
@JoinColumn(name="p_id")
public Org getParent() {
return parent;
}
public void setParent(Org parent) {
this.parent = parent;
}
}
下面是junit的測試方法:
//產生資料庫表,同時插入資料:
@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 o3=new Org();
o3.setName("分公司1的分公司1");
Org o4=new Org();
o4.setName("分公司1的分公司2");
Org o5=new Org();
o5.setName("分公司2的分公司1");
Org o6=new Org();
o6.setName("分公司1的分公司1分公司1");
o1.setParent(o);
o2.setParent(o);
o3.setParent(o1);
o4.setParent(o1);
o5.setParent(o2);
o6.setParent(o3);
o.getChildrenOrgs().add(o1);
o.getChildrenOrgs().add(o2);
o1.getChildrenOrgs().add(o3);
o1.getChildrenOrgs().add(o4);
o2.getChildrenOrgs().add(o5);
o3.getChildrenOrgs().add(o6);
try {
Session session=sf.getCurrentSession();
session.beginTransaction();
//註解中加了cascade={CascadeType.ALL},只存跟節點就把整顆樹