Sam
Sam

Reputation: 135

Unable to fetch records using unidirectional @OneToMany relationaship JPA

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.

Upvotes: 2

Views: 597

Answers (1)

Shaam
Shaam

Reputation: 151

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/

https://medium.com/@rajibrath20/the-best-way-to-map-a-onetomany-relationship-with-jpa-and-hibernate-dbbf6dba00d3

Upvotes: 4

Related Questions