Issue
I'm unable to fetch records using a unidirectional @OneToMany
relationship in JPA. Any idea if anything is missing?
Records are getting persisted though; only retrieving records is having problems.
class Employee{
int empId;
...
@OneToMany(cascade = ALL, mappedBy = "deptId",fetch = FetchType.EAGER)
List<Department> departments=new ArrayList<>();
//getters and setters
}
class Department{
String code;
....
int deptId;
//getters and setters
}
empRepository.findById(empId).getDepartments(); // is not returning rows even if records are available.
Solution
Use @JoinColumn(name = "deptId")
with @OneToMany
here is reference the best way to implement the one to Many unidirectional or Bi-directional relation in JPA
https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/
Answered By - Shaam
Answer Checked By - Cary Denson (JavaFixing Admin)