简体   繁体   English

JPA Spring Data级联删除具有组合的多对多关系

[英]JPA Spring Data cascade deletes with combined many to many relationships

I'm missing something regarding JPA cascading deletes - i'd really appreciate a pointer here. 我缺少有关JPA级联删除的信息-非常感谢您在这里提供的指导。

I have a model, simplified for this question, of three types a: 我有一个简化了此问题的模型,其中三个模型如下:

  • User That Owns Everything 拥有一切的用户
  • User can have many Groups 用户可以有多个组
  • User can have many Topics 用户可以有多个主题
  • A Topic can be added to many groups. 主题可以添加到许多组。

  • If User is deleted, all groups and topics are deleted 如果删除了用户,则所有组和主题都将删除

  • If a Group is Deleted, Topics are removed from the group but are not deleted 如果删除了一个组,则将主题从该组中删除,但不会删除
  • If a Topic is deleted, it's removed from the group and user but the User and Group remain 如果删除了主题,则会将其从组和用户中删除,但保留用户和组

So i'm just trying different Cascade per the spring data docs and not getting the results i'm describing. 所以我只是在每个春季数据文档中尝试不同的Cascade,而没有得到我正在描述的结果。 My Cascades wrong - at the moment if i delete a topic the group and user are deleted so the index is bi-directional which isn't what I want. 我的级联错误-目前,如果我删除主题,则删除组和用户,因此索引是双向的,这不是我想要的。

User: 用户:

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "owner")
private Set<Topic> topics;

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "owner")
private Set<Group> groups;

Group: 组:

@ManyToMany(cascade = {CascadeType.PERSIST})
private Set<Topic> topics;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="user_id")
@OneToOne(mappedBy = "owner", cascade = CascadeType.ALL)
private User owner;

Topic 话题

@ManyToMany(mappedBy = "topics")
private Set<EntityGroup> groups;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="user_id")
@OneToOne(mappedBy = "owner", cascade = CascadeType.ALL)
private User owner;

The thing i was missing, which seems so obvious now, is to not include a cascade value on the child objects. 我所缺少的东西(现在看来如此明显)是在子对象上不包括级联值。 In doing so, I was telling JPA to cascades deletes up to the parent. 在这样做时,我告诉JPA将删除级联到父级。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM