JPA:级联删除不会删除子级 [英] JPA: Cascade remove does not delete child

查看:656
本文介绍了JPA:级联删除不会删除子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

修改问题以更好地反映问题.最初发布的问题此处

Modifying the question to better reflect the problem. Originally posted question here

我有一个父级(Context)和一个子级(User)实体(ManyToOne关系).父级上的级联"REMOVE"不会删除子级.代码如下:

I have a parent (Context) and a child (User) entity (ManyToOne relationship). Cascade 'REMOVE' on the parent is not deleting the child. Code as below:

//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

推荐答案

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

I needed to refresh the entity before removing it:

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

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

Earlier, the entity being deleted (sampleContext) did not know that sampleUser is associated with it (probably because sampleContext was being fetched from cache). Doing a refresh before delete ensures that the entity is updated from the database.

这篇关于JPA:级联删除不会删除子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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