简体   繁体   English

带有Jointable的JPA OneToMany,删除链接将删除右侧对象

[英]JPA OneToMany with Jointable, deleting a link deletes right-side object

(OpenJPA2.x) I have Parent->(linktable)->Category relation. (OpenJPA2.x)我有Parent->(linktable)-> Category关系。 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. 我调试了jdbc查询,它由OpenJPA库执行,数据库表没有级联的删除约束。

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. 使用OneToMany注释链接Parent-> Categories。 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. 这是一个遗留应用程序,我必须使用复合主键,但是我猜这应该不是JPA问题,毕竟这是有效的sql模式模式。

You annotated the association with orphanRemoval=true . 您使用orphanRemoval=true注释了关联。 That precisely means that categories which are removed from their parent, and are thus orphan, must be removed. 这恰好意味着必须删除从其父级移除并因此成为孤儿的类别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM