10

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.

  1. How do we create Hibernate Mapping for this Employee Class?
  2. How would the Employee class look like? Does it have just a manager Id in it or it will contain another Employee Object as a member variable.

Kindly help me with this kind of scenario. Thank you.

chandra
  • 129
  • 1
  • 1
  • 8

1 Answers1

22

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<>();
 
    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

Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46
Chaitanya
  • 15,403
  • 35
  • 96
  • 137
  • is this approach effective? Suppose, You have Director, Director have manager, manager have employee. So when you open an employee, you will get a manager, inside that manager you will get employee as a child. So it will create a circular data load issue. What is the solution for that? – Sayed Uz Zaman Sep 19 '20 at 09:22
  • this kind of sucks .. you need to introduce a second column just to be able to not have hibernate blow up – mjs Aug 22 '21 at 13:35
  • @SayedUzZaman the solution is to add fetch = FetchType.LAZY in the annotations parameters – Manu de Hanoi Oct 09 '21 at 09:20