One-to-many mapping inside the same table in sleep mode

I have a table containing a primary key and a foreign key that refers to the same table. How to implement this mapping in sleep mode ... the table structure is as follows.

Dept (
    deptno pk,
    dname,
    location
)

employee (
    empid pk,
    ename,
    Manager Id Foregin key references Employee(empid),
    deptno Foregin key references dept(deptno),
    doj date,
)
+3
source share
1 answer

If the relation is bidirectional, you can have something like this:

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

    // ...
}

Nothing unusual for 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;
    }

    // ...
}
+6
source

Source: https://habr.com/ru/post/1738768/


All Articles