代码之家  ›  专栏  ›  技术社区  ›  skyman

@OneToMany双向关系返回空列表

  •  1
  • skyman  · 技术社区  · 6 年前

    我有以下几点:

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

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

    对象保持正确,但是如果我使用一个Patient对象来检索列表,则列表为空。我猜这是因为两种关系可能会发生冲突?

    这种结构的原因是,有时我们只知道患者的身份,因此我们可以从身份创建一个patient对象,但稍后我们需要使用patient对象来检索患者的详细信息(包括身份)。

    在跨国公司中,我正在创建病理学、患者和身份对象,因为它们都来自于一条消息。所以一个病人可以有很多身份和病理。然后我需要在AMQP上将病理作为JSON转发,包括一个标识。这就是它失败的地方:病理学.getPatient.getPrimaryIdentityPrimaryIdentity是从标识列表中派生出来的。

    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);
    

    我尝试了下面的方法,但只是在一个异常循环中结束

    myPatient.getUrs().add(myIdentity);
    

    我使用的是EclipseLink/Spring数据

    1 回复  |  直到 6 年前
        1
  •  1
  •   Alexander Petrov    6 年前

    你需要保持PatientId实体和两端的Patient之间的关系。最好是在Patient addIdentity(patientidenty patientidenty)中添加一个方法;

    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);