Reputation: 303
Im using JPA, MySQL and 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. They may be used on @OneToOne, @OneToMany, @ManyToOne, and @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;
Upvotes: 0
Views: 1672
Reputation: 83
You can specify orphanRemoval
if true - remove from db, if false - not remove
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;
Upvotes: 0