JPA: Cascade remove does not delete child

后端 未结 3 510
温柔的废话
温柔的废话 2021-01-19 18:09

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

I have a parent (Context) and a child (User) en

相关标签:
3条回答
  • 2021-01-19 18:58

    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.

    0 讨论(0)
  • 2021-01-19 19:00

    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.

    0 讨论(0)
  • 2021-01-19 19:04

    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/

    0 讨论(0)
提交回复
热议问题