我在使用 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
}
使用这两种方式添加新的Samples时
@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);
}
}
最佳答案
没有自动重新获取这样的东西。
您必须将样本添加到患者,而不仅仅是将患者添加到样本。
关于java - 来自一对多关系的实体仅在应用程序重启后可见(JPA 和 PostgreSQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51722424/