Wednesday, January 12, 2011

Mapping Employee to Manager in Hibernate doing a self join

I have a table containing primary key and foreign key that references same table. How can I implement this mapping in hibernate... structure of tables 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
,
)
if the relation is bidirectional, you could 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 fancy 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;

}


// ...

}

No comments:

Post a Comment