我正在尝试删除患者实体而不删除关联的OutboundMessage实体,因为我想将它们保留在数据库中以用于报告/历史目的。 这是相关代码:
患者实体
@OneToMany (mappedBy="patient", fetch = FetchType.EAGER,orphanRemoval = false)
public Set<OutboundMessage> getOutboundMessages()
{
return outboundMessages;
}
出站消息实体
@ManyToOne (fetch=FetchType.EAGER)
@JoinColumn(name = "id_patient")
public Patient getPatient()
{
return patient;
}
当我在患者端设置级联类型时,记录被删除,这不是我想要的。 当尝试如上面的代码所示(没有级联类型(时,我得到以下异常:
The DELETE statement conflicted with the REFERENCE constraint "FKqjpga9w6wp3qk26ox9pg252d9". The conflict occurred in database "MDHIS", table "dbo.tblOutboundMessage", column 'id_patient'.
拥有实体需要哪些设置才能允许删除而不级联到子实体和清理孤立记录?
谢谢!
您需要允许外键列(@JoinColumn
(中的null
值,如下所示:
@ManyToOne (fetch=FetchType.EAGER)
@JoinColumn(name = "id_patient", nullable = true)
public Patient getPatient() {
return patient;
}
然后在您的 DAO 中,您需要为与您要删除Patient
相关的所有OutboundMessage
设置null
值,然后才将其删除,如下所示:
public void deletePatient(int patientId) {
Session currentSession = sessionFactory.getCurrentSession();
// get patient with primary key
Patient patient = currentSession.get(Patient.class, patientId);
Set<OutboundMessage> messages = patient.getOutboundMessages();
//set patient id null
for(OutboundMessage message : messages) {
message.setPatient(null);
}
//delete the patient
currentSession.remove(patient);
}