0

I'm trying to map User and Script, my main goal is that a user can create many script and own many scripts but Script can be created only by one user and be owned by many

public class Script {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
@NotBlank(message = "Script name cannot be empty")
@Column(unique = true)
private String scriptName;
private boolean enabled;
@ManyToOne
private User author;
@ManyToMany(cascade = CascadeType.ALL, mappedBy = "ownedScripts")
private List<User> users = new ArrayList<>();

public class User {
@Id
@Column(updatable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
@NotBlank(message = "Username cannot be empty")
@Column(unique = true)
private String discordUsername;
@NotBlank(message = "Password cannot be empty")
private String password;
private boolean enabled;
private Role role;
@ManyToMany(cascade = CascadeType.ALL)
private List<Script> ownedScripts = new ArrayList<>();
@OneToMany(cascade = CascadeType.ALL)
private List<Script> createdScripts = new ArrayList<>();
Bugs Bunny
  • 365
  • 5
  • 19
  • 2
    [Welcome to StackOverflow](http://StackOverflow.com/tour) - Please read our [ask] page and [edit] your question to improve it. Good questions tend to receive quicker, better answers from the community. – blurfus Apr 10 '20 at 22:17
  • According to your requirements, what should happen if you delete a user ? do you expect all of its created scripts to be deleted ? do you want all of its owned scripts to be deleted ? . You simply can't put CascadeType.ALL like that. Please be clear in your question. – crazy_code Apr 11 '20 at 03:33
  • Once I delete a user I want his crated scripts to be left in the DB and the user+owned scripts to be removed @crazy_code – Bugs Bunny Apr 11 '20 at 08:30
  • 1. When user is deleted then the created scripts shouldn't be deleted for this you have to remove `cascade = CascadeType.ALL` in the User entity. (Note : By default no operations are cascaded). With this when you delete user then scripts won't be deleted 2. To delete in a many to many relationship refer this link (https://stackoverflow.com/questions/1082095/how-to-remove-entity-with-manytomany-relationship-in-jpa-and-corresponding-join) – crazy_code Apr 11 '20 at 09:25
  • Thanks for the quick replay, so I have removed the cascade from User, I understand the way to delete in MTM will implement it – Bugs Bunny Apr 11 '20 at 09:46

0 Answers0