1. 树实现通过pid进行指向上一层来实现,实体类代码如下
package com.test.model;
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
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
@JoinColumn(name="parent\_Id")
public Org getParent() {
return parent;
}
public void setParent(Org parent) {
this.parent = parent;
}
}
2.测试类代码如下, 查询时可通过递归进行查询
package com.test.test;
import org.hibernate.classic.Session;
import com.test.Util.HibernateUtil;
import com.test.model.Org;
public class StudentManager {
public static void main(String[] args) {
new StudentManager().testSave();
}
public void testSave() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Org o = new Org();
o.setName("总公司");
Org o1 = new Org();
o1.setName("分公司1");
Org o2 = new Org();
o2.setName("分公司2");
Org o21 = new Org();
o21.setName("分公司2\_1");
Org o22 = new Org();
o22.setName("分公司2\_2");
o.getChildren().add(o1);
o.getChildren().add(o2);
o1.setParent(o);
o2.setParent(o);
o2.getChildren().add(o21);
o2.getChildren().add(o22);
o21.setParent(o2);
o22.setParent(o2);
session.save(o);
testLoad();
session.getTransaction().commit();
}
public void testLoad() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Org org = (Org)session.load(Org.class, 1);
print(org, 0);
}
private void print(Org org, int level) {
String str = "----";
for(int i=0; i<level; i++) {
System.out.print(str);
}
System.out.println(org.getName());
level++;
for(Org o:org.getChildren()) {
print(o, level);
}
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章