2010-03-27 101 views
3

我有一個包含引用相同表的主鍵和外鍵的表。 我如何能實現在休眠這個映射表...的 結構如下..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

@pascal先生,請給予答覆.. – saurabh 2010-03-27 12:27:10

+0

你嘗試過什麼? 將一對多映射到自身而不是任何其他實體並沒有特別的區別。 – 2010-03-27 12:28:03

+0

@ donoroby你可以請提供上面的表格映射文件.. 其實我不知道如何映射它.... – saurabh 2010-03-27 12:33:43

回答

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; 
    } 

    // ... 
} 
+0

thanx先生爲你的迴應.. – saurabh 2010-03-28 18:05:11