JPA: Cascade remove does not delete child

99封情书 提交于 2019-12-30 23:43:10

问题


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

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

回答1:


I needed to refresh the entity before removing it:

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

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.




回答2:


You are calling remove() on sampleUser not sampleContext, and User does not cascade remove to Context, so you should only see the User being deleted.

If you call remove() on sampleContext, you must also ensure that when you created the User you added the User to the Context's users. You are most likely only setting the User's conext.




回答3:


Don't map your relation table as en entity. Use @ManyToMany Instead and make your user entity owner of the relationship.

Edit :

So your association table primary key must be composed of both foreign key.

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



来源:https://stackoverflow.com/questions/15909336/jpa-cascade-remove-does-not-delete-child

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!