Hoppo Hoppo - 2 months ago 8x
Java Question

Hibernate @ManyToOne Collection doen’t update on the fly

I'm pretty new to hibernate and @ManyToOne doesn't work. I have two DAO classes:


public class CompanyDAO implements Serializable {

@OneToMany(cascade = { DETACH, MERGE, PERSIST,REFRESH },
fetch = FetchType.EAGER,
mappedBy = " companyEmployeeReference ")
protected Collection< EmployeeDAO> employeeData = new ArrayList<EmployeeDAO>();


public class EmployeeDAO implements Serializable {

@ManyToOne(optional = false)
private CompanyDAO companyEmployeeReference;

when I then create some EmployeeDAO via

public EmployeeDAO create(EmployeeDAO o) {
return o;

and afterwards try to get this DAO from the Company side via:

public CompanyDAO getCompany(int companyID) {
CompanyDAO company = em.find(CompanyDAO.class, companyID);
return company;

it doen't work. The employeeData of the found company is always empty.

However, when I stop the server after the employee creation. And then restarted it before
everything is fine. I already search the internet (incl. stackoverflow) for hours but couldn't find the answer. The only think I found was this, but this seems to be a very manual answer, isn't there a better way?


Few clarifications. Vaguely speaking Dao is the thing which saves your entity. Not entity itself. Similar applies for @Transactional. This shouldnt be on entity level but instead on Service or Dao layer.

According to your problem - if you do this within same "session" then add to your getCompany em.refresh(company); between find and return lines.