删除JPA(FK)中的一行

删除JPA(FK)中的一行,jpa,jpa-2.0,Jpa,Jpa 2.0,假设我有三张桌子(病人、医生和药品)。Patients表有一个FK CONTAINT,它引用Doctors表中的一列,类似地,Medicines表有一个FK cnstraint,它引用Patients表中的一列。现在,当我尝试使用 //Delete From Patient Table javax.persistence.Query query = manager.createQuery("DELETE From PatientEnroll e WHERE e.no =:arg1");

假设我有三张桌子(病人、医生和药品)。Patients表有一个FK CONTAINT,它引用Doctors表中的一列,类似地,Medicines表有一个FK cnstraint,它引用Patients表中的一列。现在,当我尝试使用

//Delete From Patient Table
    javax.persistence.Query query = manager.createQuery("DELETE  From PatientEnroll e WHERE e.no =:arg1");
    int val = Integer.parseInt(no);
    query.setParameter("arg1", val);
    query.executeUpdate();
我得到以下错误:

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`acme`.`medicines`, CONSTRAINT `PatientNo` FOREIGN KEY (`PatientNo`) REFERENCES `Patients` (`PatientNo`) ON DELETE NO ACTION ON UPDATE NO ACTION)

如何从患者表中删除某些内容?

首先删除引用患者的药物:

delete from Medicine m 
where m.patient.id in (select p.id from PatientEnroll p where p.no = :arg1)
或将其与患者分离以删除:

update Medicine m set patient = null 
where m.patient.id in (select p.id from PatientEnroll p where p.no = :arg1)
否则,您显然会打破外键约束:引用不存在患者的药物将保留在数据库中。这正是外键约束的用途:避免这种不一致

请注意,除非有数百名患者有一个给定的数字,否则JPA通常的做法是:

Patient p = getPatientByNumber(args1);
em.remove(p);
如果您在关联上具有类型REMOVE的级联,则所有药物也将被删除。如果没有,您必须执行以下操作:

Patient p = getPatientByNumber(args1);
for (Medicine m : p.getMedicines()) {
    em.remove(m);
}
em.remove(p);


患者p=getPatientByNumber(args1);em.remove(p);给出了相同的错误。由于药物表中的内容涉及患者,您是否阅读了答案?您需要在OneToMany关联上级联类型REMOVE(而不是我第一次写的DELETE),这样才能工作。
Patient p = getPatientByNumber(args1);
for (Medicine m : p.getMedicines()) {
    m.setPatient(null);
}
em.remove(p);