我有一个包含引用同一个表的主键和外键的表。 如何在hibernate中实现这种映射... 表的结构如下..
Dept (
deptno pk,
dname,
location
)
employee (
empid pk,
ename,
Manager Id Foregin key references Employee(empid),
deptno Foregin key references dept(deptno),
doj date,
)
答案 0 :(得分:6)
如果关系是双向的,你可以这样:
@Entity
public class Employee implements Serializable {
private Long empid;
private String ename;
private Employee manager;
private Set<Employee> employees = new HashSet<Employee>();
private Dept deptno;
private Date doj;
@Id
@GeneratedValue
public Long getEmpid() {
return empid;
}
public void setEmpid(Long empid) {
this.empid = empid;
}
@ManyToOne
public Employee getManager() {
return manager;
}
public void setManager(Employee manager) {
this.manager = manager;
}
@OneToMany(mappedBy = "manager")
public Set<Employee> getEmployees() {
return employees;
}
public void setEmployees(Set<Employee> employees) {
this.employees = employees;
}
@ManyToOne
public Dept getDeptno() {
return deptno;
}
public void setDeptno(Dept deptno) {
this.deptno = deptno;
}
// ...
}
Dept
:
@Entity
public class Dept implements Serializable {
private Long deptno;
private String dname;
private String location;
@Id
@GeneratedValue
public Long getDeptno() {
return deptno;
}
public void setDeptno(Long deptno) {
this.deptno = deptno;
}
// ...
}