Home » Support » Forum » Foreign key constraint issue

Foreign key constraint issue

#1

Hi,

I'm trying to create two tables (Parent and Child) with a foreign key constraint from Child to Parent, so that when the parent is deleted all children are removed as well. Unfortunately, in one specific case that foreign key constraint doesn't apply and I can't figure how to make it work.

The definitions of the classes I have are as follows:

@Entity
public class Child {
    @Id
    @GeneratedValue
    private long id;

    @ManyToOne(optional = false, cascade = {})
    @JoinColumn(name="PARENT_ID", nullable = false, referencedColumnName = "id")
    private Parent parent;

    public Child(Parent parent) {this.parent = parent;}
}

@Entity
public class Parent {
    @Id
    @GeneratedValue
    private long id;

    @OneToMany(cascade = {CascadeType.MERGE, CascadeType.REMOVE}, mappedBy = "parent", orphanRemoval = true)
    List<Child> children;
}

I also have Spring repositories defined for the two classes.

Now, in the following case not all children are deleted:

...
Parent parent = new Parent();
parentRepository.save(parent);

Child child1 = new Child(parent);
childRepository.save(child1);

parent = parentRepository.findOne(...); //After this operation Parent.children is populated with child1 as expected.

Child child2 = new Child(parent);
childRepository.save(child2); // New child referring to the parent is persisted

parentRepository.delete(parent); // Here trying to delete the parent along with all children referring to it.

After the above is executed, only child1 is deleted and child2 remains. It seems that only the entities that are currently populated in the parent's list get deleted, whereas I'd want to remove all orphaned child entities (as with a foreign key constraint). Interestingly enough, if I issue delete of the parent without retrieving it first (in which case the list of children is null), both children get deleted.

Can you please help me out?

#2

Try keeping the child-parent bidirectional relationship up to date all the time, as according to JPA it is the application resposibility (when there are changes). So when a child is instantiated and it references a parent, you should also update the list in the parent to include the new child.

ObjectDB Support
ObjectDB - Fast Object Database for Java (JPA/JDO)

Post Reply

To post a reply and/or subscribe to update notifications - please login