beetri
beetri

Reputation: 1049

JPA @OneToMany not fetching the childern

Following is the table structure:

desc customer_survey
Name        Null     Type         
----------- -------- ------------ 
SURVEYID    NOT NULL VARCHAR2(10) 
CUSTNO      NOT NULL VARCHAR2(10) 
SRNO                 NUMBER(10)   
AVGRATINGS           NUMBER(5,2)  
COMMENTS             VARCHAR2(50) 
SENTON               DATE         
RESPONDEDON          DATE         

desc Survey_response
Name             Null     Type         
---------------- -------- ------------ 
SURVEYRESPONSEID NOT NULL NUMBER(10)   
RATINGS          NOT NULL NUMBER(2)    
QNO              NOT NULL VARCHAR2(10) 
SURVEYID         NOT NULL VARCHAR2(10) 

Java classes:

 public class CustomerSurvey implements Serializable {

@OneToMany(fetch=FetchType.EAGER, mappedBy="customerSurvey", 
     cascade=CascadeType.ALL)
private Set<SurveyResponse> responses;
 ......

 public class SurveyResponse {

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="SURVEYID", referencedColumnName="surveyId")
private CustomerSurvey customerSurvey;

 ......

Client code:

 List<CustomerSurvey> surveys = workService.getSurveysByCustomer("testCNo2");
 System.out.println("surveys size = " + surveys.size());

 for(CustomerSurvey survey: surveys) {
System.out.println("getting responses from the survey object now..");
Set<SurveyResponse> responses = survey.getResponses();
System.out.println("responses size= .." + responses.size());
 }

console shows:

surveys size = 1 getting responses from the survey object now.. responses size= ..0

whereas there are 7 responses in the DB for the selected survey.

Upvotes: 3

Views: 13708

Answers (3)

keesp
keesp

Reputation: 311

Another option is to populate the relationship with a jpql fetch query:

"select survey from Surveys survey join fetch survey.responses"

I had the same problem and still can't find out what is going wrong. In my case the parent entity was loaded by a jpql query, and so extending this provided a workaround

Upvotes: 0

beetri
beetri

Reputation: 1049

this link helped. I set the collection back to lazy. And
Inside persistence class, within transaction after getting the resultset, I am now calling getResponses as:

List<CustomerSurvey> surveys = query.getResultList();
for (CustomerSurvey survey : surveys) {
    Set<SurveyResponse> responses = survey.getResponses();
}

that populates the responses.

Upvotes: -1

James
James

Reputation: 18389

Enable logging and look if the SQL is correct.

It is hard to tell from your incomplete code, but in general a OneToMany should not use a JoinColumn it should use a mappedBy, and the join column in the ManyToOne should reference the Id of the object.

Also ensure you are setting both sides of the relationship when you insert your objects.

Upvotes: 4

Related Questions