Based on this example. I try to map an Employee to his manager using Hibernate and JPA annotation.
@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
}
I use hibernate criteria to write my select request. The thing is, I only want the top manager in the tree and I need a collection of his subordinates, which they also know their manager and subordinates, etc.
Criteria crit = getCurrentSession().createCriteria(Employee.class, "employee");
crit.add(Restrictions.isNull("manager"))
crit.setResultTransformer(new AliasToBeanTransformer<Employee>(Employee.class));
The result the correct Employee (top manager) that I have asked for, but the set of subordinates is empty, and if I try to change my criteria to pick an employee at the bottom of the tree, the mapping is successfully done for everything. How can I change my code to map the top manager at first. I know I could start from the bottom and access to the top manager but is there a cleaner method?