带有Jointable的JPA OneToMany,删除链接会删除右侧对象 [英] JPA OneToMany with Jointable, deleting a link deletes right-side object

查看:355
本文介绍了带有Jointable的JPA OneToMany,删除链接会删除右侧对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(OpenJPA2.x)我具有父"->(链接表)"->类别"关系.如果我从父级的类别数组中删除类别,则会从链接表( unlinked )中正确删除该类别.向数组添加新类别将插入到链接表中.但是问题是类别目标实体也从类别表中删除了.我已经调试了jdbc查询,它是由OpenJPA库执行的,数据库表没有级联的删除约束.

(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

父母->类别使用OneToMany注释链接.类别不知道从何处链接,因此希望保持该实体类尽可能整洁而没有任何链接批注.

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
}

这是一个遗留应用程序,我必须使用复合主键,但我猜这应该不是JPA问题,毕竟这是有效的sql模式模式.

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.

推荐答案

您用orphanRemoval=true注释了关联.这恰好意味着必须删除从其父级移除并因此成为孤儿的类别.

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.

这篇关于带有Jointable的JPA OneToMany,删除链接会删除右侧对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆