JPA:Cascade remove不会删除子项

时间:2013-04-09 18:08:20

标签: jpa cascade

编辑:修改问题以更好地反映问题。最初发布的问题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 个答案:

答案 0 :(得分:3)

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

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

之前,被删除的实体(sampleContext)不知道sampleUser与之关联(可能是因为sampleContext是从缓存中提取的)。在refresh之前执行delete可确保从数据库更新实体。

答案 1 :(得分:1)

您在sampleUser上调用remove()而不是sampleContext,而User不会将删除级联到Context,因此您应该只看到用户被删除。

如果在sampleContext上调用remove(),则还必须确保在创建用户时将用户添加到Context的用户。您很可能只设置用户的conext。

答案 2 :(得分:0)

不要将关系表映射为en实体。使用@ManyToMany代替并建立关系的用户实体所有者。

编辑:

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

请参阅此http://giannigar.wordpress.com/2009/09/04/mapping-a-many-to-many-join-table-with-extra-column-using-jpa/

相关问题