【问题标题】:JPA OneToMany with Jointable, deleting a link deletes right-side objectJPA OneToMany with Jointable,删除链接删除右侧对象
【发布时间】:2015-09-12 11:32:26
【问题描述】:

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

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 使用 OneToMany 注释链接。类别不知道它是从哪里链接的,因此希望尽可能保持实体类的清洁,而不需要任何链接注释。

@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 模式模式。

【问题讨论】:

    标签: java jpa jpa-2.0 openjpa


    【解决方案1】:

    您使用orphanRemoval=true 注释了关联。这恰恰意味着必须删除从其父类中删除并因此是孤儿的类别。

    【讨论】:

    • 这很简单,我的盲眼由于某种原因看不到这一点,或者我认为这意味着“如果删除父项,则删除链接表行”。显然情况并非如此。
    猜你喜欢
    • 1970-01-01
    • 2014-06-05
    • 2011-01-01
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    相关资源
    最近更新 更多