我使用以下代码在 Hibernate ORM 中定义了实体关系:
@Entity
public class Treatment {
@OneToMany(fetch = FetchType.EAGER, mappedBy="treatment")
private List<Consultation> consultations;
...
}
@Entity
public class Consultation {
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name = "treatment_id")
private Treatment treatment;
...
}
我的问题是,当我想建立联系时,我应该如何更新治疗/咨询? 一侧更新是否足够:
treatment.getConsultations().add(newCon);
或者我应该两边都更新吗?
treatment.getConsultations().add(newCon);
newCon.setTreatment(treatment);
删除后效果如何?
最佳答案
好吧,使用mappedBy你告诉Hibernate该关系是由另一方维护的,这是一个在Consultation类中称为treatment的字段。所以首先要获取咨询实例,然后设置处理,最后持久化咨询实例。它将更新数据库中的所有引用作为完整性约束(主键/外键对)。所以这里的咨询表会有一个treatmentId外键列指向Treatment表的ID列(主键)。
示例代码是,
Consultation consultation = new Consultation();
// This maintains the relationship.
consultation.setTreatment(treatment);
someDaoRepository.save(consultation);
希望这有帮助,快乐编码!
关于java - Hibernate/JPA OneToMany 是否应该在两侧进行更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41218036/