我有两个可持久的实体Obj1和Obj2。 Obj2包含对Obj的引用,如下所示。在Obj1中没有对Obj2的引用(在代码级别 - Java)。
public class Obj2{
....
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE}, optional = true)
private Obj1 obj1;
我按照建议用@OneToMany更新了Ojbj 1:
public class Obj1{
....
@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE,CascadeType.ALL},orphanRemoval = true)
private List<Obj2> obj2;
当我尝试删除Obj1时:
em.remove(obj1Instance)
由于Foreigh Key constaint
而失败00:35:23,109 WARN [com.arjuna.ats.arjuna] (http--127.0.0.1-8080-1) ARJUNA012125: TwoPhaseCoordinator.beforeCompletion - failed for SynchronizationImple< 0:ffff7f000101:-7f20c644:5369716f:26, org.hibernate.engine.transaction.synchronization.internal.RegisteredSynchronization@dcedf7 >: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`my_db`.`obj2`, CONSTRAINT `FKC4783505BB5D6339` FOREIGN KEY (`obj1_pk`) REFERENCES `obj1` (`pk`))
...
... 94 more
Caused by: org.hibernate.exception.ConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`my_db`.`obj2`, CONSTRAINT `FKC4783505BB5D6339` FOREIGN KEY (`obj1_pk`) REFERENCES `obj1` (`pk`))
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`my_db`.`obj2`, CONSTRAINT `FKC4783505BB5D6339` FOREIGN KEY (`obj1_pk`) REFERENCES `obj1` (`pk`))
我(错误地看来!)认为CascadeType.REMOVE会照顾这个?我该如何处理这个删除?
/ T
答案 0 :(得分:1)
手动处理或在Obj1中添加反向关系@OneToMany(orphanRemoval=true)
。
答案 1 :(得分:1)
感谢帮助人员...我设法通过(某种程度)结合两条建议并改变了外键,以便在DELETE上进行CASCADE。
答案 2 :(得分:0)
您何时添加optional = true
?是在部署应用程序之前还是之后?如果是之后,MySQL将不会更新my_db
。obj2
上的NotNull约束,检查列
是否为Nullable。如果不是,请删除并添加约束obj1_pk
obj1_pk
,使其可以为Nullable。
或者你可以简单地删除这两个表并重新创建它们。