Hibernate OneToMany and ManyToOne confusion! List of zeros!

I have two tables ... For example, a company and an employee (let it be very simple)

Company( id, name ); Employee( id, company_id ); 

Employee.company_id is a foreign key.

My model entity looks like this:

Employee

 @ManyToOne(cascade = CascadeType.PERSIST) @JoinColumn(name = "company_id") Company company; 

Company

 @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "company_id") List<Employee> employeeList = new ArrayList<Employee>(); 

So yes, I want a list of employees for the company.

When I do the following ...

 Employee e = new Employee(); e.setCompany(c); //c is an Company that is already in the database. DAO.insertEmployee(e); //this works fine! 

If I receive an object of my company, the list is empty!

Ive tried endless different ways from the Hibernate documentation!

Obviously, I have not tried the right one yet!

I just want the list to be filled out for me or to find a reasonable alternative.

Help will be greatly appreciated, thanks!

+4
source share
2 answers

You need to make the relationship bidirectional. You have two unidirectional. Add mappedBy = "company" to employeeList . This means sleep mode, the list of employees is just a backlink from Employee to Company

 @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "company") List<Employee> employeeList = new ArrayList<Employee>(); 
+5
source

I donโ€™t think you should List<Employee> employeeList = new ArrayList<Employee>(); This should be done if you have identified a party that has a list as your own party, which in your case is an Employee and not a company. I think every time you download a company instance, you get a new employeeList instance, but you are not sure. But of course, there is no need to instantiate a new ArrayList each time.

0
source

Source: https://habr.com/ru/post/1337157/


All Articles