0

Based on this example. I try to map an Employee to his manager using Hibernate and JPA annotation.

Table Employee

@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?

Alex L
  • 185
  • 1
  • 11
  • Your query is invalid. There is no field named "manager_id" in the class Employee. HQL/Criteria never use table and column names. They work on entities, their fields and their associations. So you want `crit.add(Restrictions.isNull("employee.manager"))`. How do you test that the list of subordinates is empty? Show us a complete test case, with example data. Also, cascade=ALL on a ManyToOne is incorrect. You don't want to delete an employee's manager when you delete the employee. – JB Nizet Dec 23 '15 at 16:20
  • Sorry I edited it. it is 'manager'. – Alex L Dec 23 '15 at 16:24
  • hi, what is about jpa CriteraiBuilder instead of Hobgernate Criteria? – George Vassilev Dec 24 '15 at 07:32

1 Answers1

0

After few days of research, I found the problem

.setResultTransformer(new AliasToBeanTransformer<Employee>(Employee.class));

The solution was to change the mapping on my result beacause 'Each row of results is a distinct instance of the root entity'

.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
Alex L
  • 185
  • 1
  • 11