代码之家  ›  专栏  ›  技术社区  ›  Neo

JPA:级联删除不会删除子项

  •  4
  • Neo  · 技术社区  · 13 年前

    编辑:修改问题以更好地反映问题。最初发布的问题 here

    我有一个父母( Context )还有一个孩子( User )实体(ManyToOne关系)。父级上的级联“REMOVE”没有删除子级。代码如下:

    //Owning side - child
    @Entity
    public class User {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private int id;
        @Column(name = DBColumns.USER_NAME)
        private String name;
        @ManyToOne
        @JoinColumn(name = DBColumns.CONTEXT_ID)
        private Context context;
    }
    
    //parent
    @Entity
    public class Context {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private int id;
        @Column(name = DBColumns.CONTEXT_NAME)
        private String name;
        @OneToMany(mappedBy = "context", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true)
        private Set<User> users = new HashSet<User>();
    }
    
    //usage
    Context sampleContext = new Context("sampleContext");
    em.persist(sampleContext);
    User sampleUser = new User(sampleContext, "sampleUser");
    em.persist(sampleUser);
    em.remove(sampleContext); //should remove user as well but throws foreign key dependency error
    
    3 回复  |  直到 13 年前
        1
  •  3
  •   Neo    13 年前

    在删除实体之前,我需要刷新它:

    em.refresh(sampleContext);
    em.remove(sampleContext);
    

    早些时候,被删除的实体( sampleContext )不知道 sampleUser 与之相关(可能是因为 示例上下文 正在从缓存中提取)。正在执行 refresh 之前 delete 确保从数据库中更新实体。

        2
  •  1
  •   James    13 年前

    您对sampleUser而不是sampleContext调用remove(),并且User不会将remove级联到Context,因此您应该只看到正在删除的User。

    如果您对sampleContext调用remove(),还必须确保在创建User时,您将User添加到了Context的用户中。您很可能只是在设置用户的上下文。

        3
  •  0
  •   Gab    13 年前

    不要将关系表映射为实体。使用 @ManyToMany 相反,让您的用户实体成为关系的所有者。

    编辑:

    因此,您的关联表主键必须由两个外键组成。

    看看这个 http://giannigar.wordpress.com/2009/09/04/mapping-a-many-to-many-join-table-with-extra-column-using-jpa/