树状映射
这种方案固定、通用,下面以公司组织结构为例,要实现的树状图如图所示:
Org 组织类:
1 package com.bjsxt.hibernate; 2 3 import java.util.HashSet; 4 import java.util.Set; 5 6 import javax.persistence.CascadeType; 7 import javax.persistence.Entity; 8 import javax.persistence.FetchType; 9 import javax.persistence.GeneratedValue; 10 import javax.persistence.Id; 11 import javax.persistence.JoinColumn; 12 import javax.persistence.ManyToOne; 13 import javax.persistence.OneToMany; 14 15 @Entity 16 public class Org { 17 18 //节点id 19 private int id; 20 21 //节点名 22 private String name; 23 24 private Set<Org> children = new HashSet<Org>(); 25 26 private Org parent; 27 28 @Id 29 @GeneratedValue 30 public int getId() { 31 return id; 32 } 33 34 public void setId(int id) { 35 this.id = id; 36 } 37 38 public String getName() { 39 return name; 40 } 41 42 public void setName(String name) { 43 this.name = name; 44 } 45 46 //cascade=CascadeType.ALL CUD操作能级联添加、更新、删除 47 //mappedBy="parent" 以Org的parent属性为准 48 //fetch=FetchType.EAGER 设置为 EAGER 模式,马上该对象的所有属性,而不是懒加载 49 @OneToMany(cascade=CascadeType.ALL,mappedBy="parent",fetch=FetchType.EAGER) 50 public Set<Org> getChildren() { 51 return children; 52 } 53 54 public void setChildren(Set<Org> children) { 55 this.children = children; 56 } 57 58 //ManyToOne 多个子节点对应一个父节点 59 //JoinColumn(name="parent_id") 外键的字段名:parent_id 60 @ManyToOne 61 @JoinColumn(name="parent_id") 62 public Org getParent() { 63 return parent; 64 } 65 66 public void setParent(Org parent) { 67 this.parent = parent; 68 } 69 }
保存和获取节点:
1 @Test 2 public void testSave(){ 3 //设置节点结构 4 Org org = new Org(); 5 org.setName("总公司"); 6 Org org1 = new Org(); 7 org1.setName("分公司1"); 8 Org org2 = new Org(); 9 org2.setName("分公司2"); 10 Org org11 = new Org(); 11 org11.setName("分公司1下部门1"); 12 Org org12 = new Org(); 13 org12.setName("分公司1下部门2"); 14 15 org.getChildren().add(org1); 16 org.getChildren().add(org2); 17 org1.getChildren().add(org11); 18 org1.getChildren().add(org12); 19 org11.setParent(org1); 20 org12.setParent(org1); 21 org1.setParent(org); 22 org2.setParent(org); 23 24 Session session = sf.getCurrentSession(); 25 session.beginTransaction(); 26 //因为配置了cascade=CascadeType.ALL能够进行级联更新,所以只要保存根节点就能插入所有的子节点 27 session.save(org); 28 session.getTransaction().commit(); 29 } 30 31 @Test 32 public void testLoad(){ 33 testSave(); 34 35 Session session = sf.getCurrentSession(); 36 session.beginTransaction(); 37 Org org = (Org) session.load(Org.class, 1); 38 //递归输出所有节点 39 print(org,0); 40 session.getTransaction().commit(); 41 } 42 43 //输出方法 44 private void print(Org org,int level) { 45 String preStr = ""; 46 for(int i=0;i<level;i++){ 47 preStr += "----|"; 48 } 49 50 System.out.println(preStr + org.getName()); 51 for(Org o:org.getChildren()){ 52 //如果有子节点,则继续往下递归 53 print(o,level+1); 54 } 55 }
jar包链接: https://pan.baidu.com/s/1gf9nQoV 密码: 3uvj
代码链接: https://pan.baidu.com/s/1i4CXylf 密码: 8uau