Question

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

Was it helpful?

Solution 2

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.

OTHER TIPS

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

When did you add optional = true? Is it before deploying the application or after? If it is after, MySQL wouldn't update the NotNull constraint on my_db.obj2, check if column obj1_pk is Nullable. If it is not, drop and add the constraint FKC4783505BB5D6339 so it can be Nullable. Or you can simply drop these two tables and recreate them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top