Hibernate does't update joined collection

102 views Asked by At

I have an Employee entity (employee(id,name,company_id)):

@Entity
public class Employee {
    @Id
    @Column(name="ID")
    private Integer id; 

    @ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
    @JoinColumn(name = "COMPANY_ID")
    private Company company;
    ...
}

and I have a Company entity (company(id,name)):

@Entity
public class Company {
    @Id
    @Column(name="ID")
    private Integer id; 

    @OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
    @JoinColumn(name="COMPANY_ID")
    @Where(clause="status_code = '1'")
    private Set<Employee> employeeSet;
    ...
}

A company can have more employees, but one employee belongs to one company at a time. I joined them (I want to get the employees with status 1) and set cascade to all, but when I update an employee to be at another company then the employeeSet in the company doesn't refresh, nor the old neither the new company. This is the update method for the employee:

sessionFactory.getCurrentSession().merge(employee);

I tried with update(employee) too, but no success. What do I miss from the code?

1

There are 1 answers

4
Predrag Maric On BEST ANSWER

First, your employeeSet mapping is wrong. Change it to

@OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy = "company")
@Where(clause="status_code = '1'")
private Set<Employee> employeeSet;

Second, you need to handle the other side of the relation as well, meaning you need to add the employee to the new company's employeeSet and remove it from the old one. This is necessary in order to maintain consistency of companies already loaded into hibernate session.