一对多关系中的实体仅在应用程序重新启动后可见(JPA和PostgreSQL)

时间:2018-08-07 08:39:30

标签: java postgresql jpa jta

我在使用JPA时存在实体关系问题。

我有这两个JPA实体。当应用程序使用<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>

启动时,两个表均由应用程序创建
@Entity(name = "patient")
public class Patient {

    @XmlID
    @XmlElement
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    private Integer id;

    private Integer height;

    private Integer weight;

    @XmlJavaTypeAdapter(YearAdapter.class)
    @Temporal(TemporalType.TIMESTAMP)
    private Date yearOfBirth;

    private Sex sex;

    @OneToMany(mappedBy = "patient", fetch = FetchType.LAZY)
    private List<Sample> samples;

   // Getters and Setters omitted
}

@Entity(name = "sample")
public class Sample {

    @XmlID
    @XmlElement
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    private Integer id;

    private boolean aliquotated;

    private BigDecimal initialVolume;

    private BigDecimal availableVolume;

    @XmlIDREF
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "patient_id")
    private Patient patient;

   // Getters and Setters omitted
}

使用这两种方法添加新样本时

@PersistenceContext(unitName = "postgres-hcc")
private EntityManager em;

/* ... */

@Transactional
public Sample storeSample(Sample sample) {

    sample.setAvailableVolume(sample.getInitialVolume());

    em.persist(sample);

    return sample;
}

@Transactional
public Sample storeSample(SampleDTO sampleDTO) {

    Sample sample = new Sample();

    sample.setInitialVolume(sampleDTO.getInitialVolume());
    sample.setAliquotated(sampleDTO.isAliquotated());
    sample.setPatient(patientService.getPatient(sampleDTO.getPatientId()));

    return this.storeSample(sample);
}
提取患者时,新样本不可见; samples列表为空。但是它们被写入数据库。另外,在不使用drop-and-create选项的情况下重新启动应用程序之后,所有样本(写入数据库的样本)都将在samples列表中可见。

我感觉这与将新样本添加到患者后如何获取而不重新获取链接的样本有关。因此它们会在应用程序重启后出现。

在这种情况下是否可以做任何事情或需要进行重大更改?


其他信息 获取患者:

public List<Patient> getPatients() {
    TypedQuery<Patient> q = em.createQuery("SELECT p FROM patient p", Patient.class);

    if (q == null) {
        return null;
    }

    return q.getResultList();
}

public Patient getPatient(Integer patientId) {
    Patient patient = em.find(Patient.class, patientId);

    if (patient != null) {
        return patient;
    } else {
        throw new NotFoundException("No patient with id " + patientId);
    }
}

1 个答案:

答案 0 :(得分:0)

没有自动重新获取之类的东西。

您不仅必须将样本添加到患者,还必须将样本添加到患者。

相关问题