I was asked how I would create a hibernate mapping for a column in a table that refers to the primary key of the table.
For example, an Employee table has EMP_ID as primary key and it also has MGR_ID column to know the manager of the employee. As a manager is also an Employee, it would be in the same table. Hence every Employee row has a manager Id which is also an employee.
Kindly help me with this kind of scenario. Thank you.
You can have a reference to the manager
in your Employee
class.
The entity looks like this:
@Entity
@Table(name="EMPLOYEE")
public class Employee {
@Id
@Column(name="EMPLOYEE_ID")
@GeneratedValue
private Long employeeId;
@Column(name="FIRSTNAME")
private String firstname;
@Column(name="LASTNAME")
private String lastname;
@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="manager_id")
private Employee manager;
@OneToMany(mappedBy="manager")
private Set<employee> subordinates = new HashSet<employee>();
public Employee() {
}
public Employee(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
// Getter and Setter methods
}
Refer to this link for complete example:
Hibernate Self Join Annotations One To Many mapping example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With