0

I have a Parent class pointing to a Child class:

public class Parent {

    @OneToOne
    private Child child;

}

public class Child {

}

Is there a way to delete a Child without getting a constraint Exception ?

Caused by: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails

P.S: I'm not entirely sure I've modeled this properly. A Parent can be pointing to one Child but an instance of a Child can be pointed to by more than one Parent. What I'd like to do is to delete a Child and have it's references among all Parents removed. Hope you understand.

James P.
  • 19,313
  • 27
  • 97
  • 155
  • If a Child can have more than one Parent, then the `@OneToOne` is wrong, you nee to use `@OneToMany` in the Parent. And use something like this in the `Child`: `@ManyToOne List parents` – Arturo Volpe Jul 25 '14 at 02:04
  • See this: http://stackoverflow.com/questions/9944137/have-jpa-hibernate-to-replicate-the-on-delete-set-null-functionality – Arturo Volpe Jul 25 '14 at 02:12

1 Answers1

2

From this I think you need to do two things:

Fix relations

public class Parent {

    @ManyToOne(optional=true)
    private Child child;

}

public class Child {

    @OneToMany
    private Set<Parent> parents;
}

Implements a remove method:

void removeChild(Child toRemove) {
    for (Parent p : toRemove.getParents())  {
        p.setChild(null);
        em.merge(p);
    }
    em.delete(toRemove);
}
Community
  • 1
  • 1
Arturo Volpe
  • 3,442
  • 3
  • 25
  • 40