需求:
组织表 (存在上下级关系 ) 如:总公司、分公司、部门。
在数据库中设计
通过 id 和pid来实现这种继承关系
CREATE TABLE `org` (
`id` int(11) NOT NULL default '0',
`pid` int(11) default NULL,
`name` varchar(40) default NULL,
PRIMARY KEY (`id`),
KEY `pid` (`pid`),
CONSTRAINT `org_ibfk_1` FOREIGN KEY (`pid`) REFERENCES `org` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
实践应用中,通过逆向工程,可以生成对应的Org的类,我们来看一下他的源码
面向对象 的类的设计,是把org当成一个链表集合,如果该组织下有分支,则set集合中有值。(为什么是set,因为每个组织的id唯一标识它)。
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.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Org entity. @author MyEclipse Persistence Tools
*/
@Entity
@Table(name = "org", catalog = "hibernate")
public class Org implements java.io.Serializable {
// Fields
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private Org org;
private String name;
private Set<Org> orgs = new HashSet<Org>(0);
// Constructors
/** default constructor */
public Org() {
}
/** minimal constructor */
public Org(Integer id) {
this.id = id;
}
/** full constructor */
public Org(Integer id, Org org, String name, Set<Org> orgs) {
this.id = id;
this.org = org;
this.name = name;
this.orgs = orgs;
}
// Property accessors
@Id
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "pid")
public Org getOrg() {
return this.org;
}
public void setOrg(Org org) {
this.org = org;
}
@Column(name = "name", length = 40)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "org")
public Set<Org> getOrgs() {
return this.orgs;
}
public void setOrgs(Set<Org> orgs) {
this.orgs = orgs;
}
}