简体   繁体   English

JPA Spring Boot删除时删除参考?

[英]JPA Spring boot remove reference on delete?

Im using JPA, MySQL and Spring boot我正在使用 JPA、MySQL 和 Spring Boot

I cant for the life of me figure out how to apply cascades, the documentation doesnt seem to apply what I intend:我一生都无法弄清楚如何应用级联,文档似乎没有应用我的意图:

eg.例如。 https://hellokoding.com/deleting-data-with-jpa-hibernate/ Use CascadeType.ALL or CascadeType.REMOVE attributes to delete the child entities when the parent entity is deleted. https://hellokoding.com/deleting-data-with-jpa-hibernate/删除父实体时,使用 CascadeType.ALL 或 CascadeType.REMOVE 属性删除子实体。 They may be used on @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany它们可用于@OneToOne、@OneToMany、@ManyToOne 和 @ManyToMany

^ I don't want to remove child entities I want to ONLY remove reference ^ 我不想删除我只想删除引用的子实体

my guess is this relationship is many-to-many?我猜这种关系是多对多的吗?

many users can have many modules
many modules can have many users

How do I get it to apply this via cascade annotation?如何让它通过级联注释应用它?

when a user is deleted the module is not

when a module is deleted its reference is removed from user

when a user is added a module is not

when a module is added a user is not

Current entity:当前实体:

@Entity
@Table(name = "module")
public class Module {
    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "modules")
    private Set<User> users;

You can specify orphanRemoval if true - remove from db, if false - not remove您可以指定orphanRemoval如果为真 - 从数据库中删除,如果为假 - 不删除

For ManyToMany对于多对多

@ManyToMany
@Cascade(value = org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
private Set<User> users;

For OneToMany一对多

@OneToMany(mappedBy = "topic", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<User> users;

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

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