2012-07-27 32 views
2

假设我有三张表格(患者医生和药物)。 “患者”表具有引用医生表中的列的FK约束,并且类似地,“药品”表具有引用“患者”表中的列的FK cnstraint。现在,当我尝试使用删除JPA中的一行(FK)

//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) 

如何删除从患者桌上的东西?

回答

3

删除的药品第一参考患者:

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

如果你有型的级联的关联中删除,所有药物也将被删除。如果没有,你就必须做:

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

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

患者P = getPatientByNumber(args1); em.remove(p);给出同样的错误。由于药物表中的内容引用患者行 – Murphy316 2012-07-27 16:39:49

+1

您是否阅读过答案?您需要在OneToMany关联上使用类似REMOVE的级联(而不是像我第一次写的那样删除),才能使其工作。 – 2012-07-27 16:56:13

+0

谢谢..我错过了那部分 – Murphy316 2012-07-27 17:04:04