JPA OneToMany with Jointable, deleting a link dele

2019-09-09 22:07发布

问题:

(OpenJPA2.x) I have Parent->(linktable)->Category relation. If I remove category from parent's category array it gets properly deleted from the linktable (unlinked). Adding a new category to an array gets inserted to the linktable. However problem is category target entity is also deleted from Category table. I have debugged jdbc queries and it's performed by OpenJPA library, db tables don't have a cascaded delete constraint.

Parent(key=ServerId,Code)
ServerId|Code |Name
1       |code1|name1
1       |code2|name2
1       |code3|name3
2       |code1|name4
Category(key=ServerId,Code)
1       |cat1 |child1
1       |cat2 |child2
2       |cat2 |child3
LinkTable(key=ServerId,PCode,CCode) 
ServerId|PCode|CCode
1       |code1|cat1
1       |code1|cat2
1       |code3|cat1

Parent->Categories are linked using OneToMany annotation. Category does not know where it was linked from so prefer keeping that entity class clean as possible without any link annotations.

@Entity @Table(name="Parent") @Access(AccessType.FIELD)
public class Parent {
   @EmbeddedId Parent.PK pk; // contains serverId+code fields
   private String name;
   @OneToMany(fetch=FetchType.LAZY, orphanRemoval=true, cascade=CascadeType.PERSIST)
   @JoinTable(name="LinkTable",
     joinColumns={
       @JoinColumn(name="ServerId", referencedColumnName="ServerId", nullable=false),
       @JoinColumn(name="PCode", referencedColumnName="Code", nullable=false)           
     },
     inverseJoinColumns={
       @JoinColumn(name="ServerId", referencedColumnName="ServerId", nullable=false),
       @JoinColumn(name="CCode", referencedColumnName="Code", nullable=false)
     }
   )
   private List<Category> cats;
   public List<Category> getCategories() { return cats; }
}

@Entity @Table(name="Category") @Access(AccessType.FIELD)
public class Category {
  @EmbeddedId Category.PK pk; // serverId,Code fields
  private String name;
  // this entity don't have OneToMany,ManyToOne,etc.. links back to parent
}

This is a legacy application I must use a composited primary keys, but it should not be a JPA problem I guess, after all this is a valid sql schema pattern.

回答1:

You annotated the association with orphanRemoval=true. That precisely means that categories which are removed from their parent, and are thus orphan, must be removed.