1

I am trying to delete child entry from the table and my entity has 2-way relation. I got an exception "Cannot delete or update a parent row: a foreign key constraint fails". I need mapping when I delete child entry relation with parent automatically dropped.

@Entity
@Table
public class RuleModel implements Comparable<RuleModel>    {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Rule_Id", unique = true, nullable = false)
    protected Integer id;

    @OneToOne(fetch = FetchType.EAGER)
    protected RuleModel parent;

    @OneToOne(fetch = FetchType.EAGER)
    protected RuleModel child;
}
Hammad
  • 101
  • 1
  • 10

2 Answers2

0

You have to break the relation between the object before deleting the child.

Zorglube
  • 664
  • 1
  • 7
  • 15
0

I set both parent and child null in pre-remove block so hibernate first update relations to null and then delete

@PreRemove
public void preRemove() {

    if (parent != null) {
        parent.setChild(null);
    }
    if (child != null) {
        child.setParent(null);
    }
}
Hammad
  • 101
  • 1
  • 10
  • 1
    Your design is error prone. You don't really need to store parent and child separately as you are doing in DB. Just treat them as 2 directions of same relationship will be better, which means simply store "parent" in DB, and map it in your entity. For the child relationship, use `mappedBy`. And, perform these in your domain logic, instead of relying on `@PreRemove`. Though you can delete the thing now, your parent is now pointing to no child and your child is under no parent, which looks to be some data inconsistency to me. – Adrian Shum Oct 12 '16 at 01:50
  • I am building 2 way link list – Hammad Oct 12 '16 at 08:49
  • so? That's actually even worse. if you remove a node from a doubly linked list, its prev's next should point to node's next and its next's prev should point to node's prev. What you are doing is simply corrupting the list. And, what I said in prev comment has no contradiction with what you are trying to do. In DB you only need to store the parent ID, and in your entity model, you can have both directions of that relationship like what you are doing now – Adrian Shum Oct 12 '16 at 08:57