简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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