简体   繁体   中英

Hibernate JPA many-to-one self-join association cascade, how to select the top hierarchy and map children?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM