问题描述
我有两个持久化实体Obj1和Obj2。 Obj2包含如下的Obj引用。在Obj1中没有对Obj2的引用(在代码级别 - Java)。
I have two persistable entities Obj1 and Obj2. Obj2 contains a reference to Obj like below. There is no reference (at code level - Java) to Obj2 in Obj1.
public class Obj2{
....
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE}, optional = true)
private Obj1 obj1;
使用@OneToMany更新了Ojbj 1,如下所示:
I updated Ojbj 1 with @OneToMany as suggested:
public class Obj1{
....
@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE,CascadeType.ALL},orphanRemoval = true)
private List<Obj2> obj2;
当我尝试删除Obj1时:
When I try to delete Obj1:
em.remove(obj1Instance)
Key constaint
It fails due to 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`))
我有(似乎错了!)假定C ascadeType.REMOVE会照顾这个吗?我应该如何处理这个删除?
I had (wrongly it seems!) asumed that CascadeType.REMOVE would take care of this? How should I handle this delete?
/ T
推荐答案
谢谢对于帮助家伙......我设法通过结合这两条建议来做到这一点,并且我修改了外键,这样它就可以在DELETE上级联。
Thanks for the help guys... I managed to do it by (sort of ) combining both pieces of advice and I altered the Foreign Key so that it would CASCADE on DELETE.
这篇关于休眠:不能删除对象 - 外键约束 - CascadeType.REMOVE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!