树形结构的关系,在数据库中的设计一般也就是id\pid这样.对于Hibernate来说.其实也就在同一个类中自己对自己做一对多和多对一的双向关系映射.
代码如下.
package com.eneitys;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
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> childrens=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)//mappedBy的值为在多的一方对一的引用的属性名
public Set<Org> getChildrens() {
return childrens;
}
public void setChildrens(Set<Org> childrens) {
this.childrens = childrens;
}
@ManyToOne
@JoinColumn(name="parent_id")//指定多对一的外键字段名,这里如果不写JoinColumn,会多一个字段!
public Org getParent() {
return parent;
}
public void setParent(Org parent) {
this.parent = parent;
}
}