Hibernate中同一个表中的一对多映射

sau*_*abh 3 java orm hibernate

我有一个表包含引用相同表的主键和外键.如何在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,
)
Run Code Online (Sandbox Code Playgroud)

Pas*_*ent 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;
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

没什么好看的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;
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)