需求分析:
总公司下有两个分公司 1 和 2,其中,分公司1下又有两个部门 1 和 2 。
1.数状结构的数据库设计
ID | Parent_ID | NAME | ... |
1 | NULL | 总公司 | |
2 | 1 | 分公司1 | |
3 | 1 | 分公司2 | |
4 | 2 | 分公司1下部门1 | |
5 | 2 | 分公司1下部门2 |
2.Hibernate下的编程设计
Org.java文件,使用Hibernate Annotation
package com.lk.pojo;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name="M_ORG")
@SequenceGenerator(name="SEQ_NO",sequenceName="SEQ_M_OGR", allocationSize = 1)
public class Org {
private int id;
private String name;
private Set<Org> chilren = new HashSet<Org>();
private Org parent;
@Id
@Column(name="SEQ_NO")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_NO")
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> getChilren() {
return chilren;
}
public void setChilren(Set<Org> chilren) {
this.chilren = chilren;
}
@ManyToOne
@JoinColumn(name="pid")
public Org getParent() {
return parent;
}
public void setParent(Org parent) {
this.parent = parent;
}
}
3.树状结构的遍历显示
遍历树状结构的数据一般采用递归操作,如下:
private void print(Org o, int level) {
String preStr = "";
for(int i=0;i<level;i++){
preStr +="==";
}
System.out.println(preStr+o.getName());
for(Org child : o.getChilren()){
print(child,level+1);
}
}