如何删除父母而不删除一对多关系中的孩子

时间:2018-06-24 18:54:31

标签: java hibernate cascade orphaned-objects

我想删除一个Patient实体而不删除关联的OutboundMessage实体,因为我想将它们保留在数据库中以进行报告/历史记录。这是相关的代码:

患者实体

std::unordered_set

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;
}

拥有实体需要哪些设置才能允许删除而无需级联到子实体并且不清除孤立记录?

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要在外键列(null)中允许@JoinColumn的值,如下所示:

@ManyToOne (fetch=FetchType.EAGER)
@JoinColumn(name = "id_patient", nullable = true)
public Patient getPatient() {
    return patient;
}

然后,在您的DAO中,您需要为与要删除的null相关的所有OutboundMessage设置Patient的值,然后才将其删除,如下所示:

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);
}