如何在一对多关系中删除 parent 而不删除 children

How to delete parent without deleting children in one to many relationship

我试图在不删除关联的 OutboundMessage 实体的情况下删除 Patient 实体,因为出于 reporting/historical 目的,我想将它们保留在数据库中。这是相关代码:

患者实体

@OneToMany (mappedBy="patient", fetch = FetchType.EAGER,orphanRemoval = false)
public Set<OutboundMessage> getOutboundMessages() 
{
    return outboundMessages;
}

OutboundMessage 实体

@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'.

拥有实体需要什么设置才能允许删除而不级联到 children 个实体并且不清除孤立记录?

谢谢!

您需要在外键列 (@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);
}