skyman
skyman

Reputation: 2335

@OneToMany bidirectional relation returns null List

I have the following:

@Entity
@Table(name = "patient_identifiers")
public class PatientIdentity extends AbstractEntity {
    @ManyToOne
    @JoinColumn(name = "patient_id")
    private Patient patient;

and

@Entity
@Table(name = "patients")
public class Patient extends AbstractEntity {
    @OneToMany(mappedBy = "patient", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<PatientIdentity> urs;

The objects persist correctly, however if I use a Patient object to retrieve the List the list is null. I am guessing that it is something to do with having the two relationships that maybe conflict?

The reason for the structure is that sometimes we only know the identities for a patient so we can create a patient object from an identity, but later we need to use the patient object to retrieve the details of the patient (including identities).

Within a transnational, I am creating Pathology, Patient and Identity objects as they are all derived from a single message. So a Patient can have many identities and pathologies. I then need to forward the pathology as JSON over AMQP including an identity. This is where it fails: Pathology.getPatient.getPrimaryIdentity The PrimaryIdentity is derived from the List of identities.

myIdentity = new PatientIdentity();
myIdentity.setUr(ur);
myIdentity.setCreated(new Date());
myIdentity.setPrimary(true);
patientIdentityService.create(myIdentity);

Patient myPatient = new Patient();
myPatient.setDateOfBirth(dateOfBirth);
myPatient.setDateOfDeath(dateOfDeath);
myPatient.setLastUpdated(new Date());
repo.saveAndFlush(myPatient);

myIdentity.setPatient(myPatient);

I tried the following but just ended in a loop of Exceptions

myPatient.getUrs().add(myIdentity);

I am using EclipseLink / Spring Data

Upvotes: 1

Views: 85

Answers (1)

Alexander Petrov
Alexander Petrov

Reputation: 9492

You need to maintain the relationship between PatientIdentity and Patient on both ends. The best would be to add a method in Patient addIdentity(PatientIdentity patientIdentity);

public void addIdentity(PatientIdentity patientIdentity) {
   if (urs=null) {
      urs = new ArrayList<PatientIdentity>();
   }
   urs.add(patientIdentity);
   patientIdentity.setPatient(this);
}

    myIdentity = new PatientIdentity();
    myIdentity.setUr(ur);
    myIdentity.setCreated(new Date());
    myIdentity.setPrimary(true);
   // you don't need this code any longer since you are cascading your persist. 
   //patientIdentityService.create(myIdentity);

    Patient myPatient = new Patient();
    myPatient.setDateOfBirth(dateOfBirth);
    myPatient.setDateOfDeath(dateOfDeath);
    myPatient.setLastUpdated(new Date());

    myPatient.addIdentity(myIdentity);

    // this will cascade the persist
    repo.saveAndFlush(myPatient);

Upvotes: 1

Related Questions