Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

java - Hibernate: Cannot Delete Object - foreign key constraint - CascadeType.REMOVE

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;

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;

When I try to delete Obj1:

em.remove(obj1Instance)

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

I had (wrongly it seems!) asumed that CascadeType.REMOVE would take care of this? How should I handle this delete?

/T

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Either handle it manually or add a reverse relationship @OneToMany(orphanRemoval=true) in Obj1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...