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<>();
5
  • 2
    Welcome to StackOverflow - Please read our How to Ask page and edit your question to improve it. Good questions tend to receive quicker, better answers from the community.
    – blurfus
    Apr 10, 2020 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, 2020 at 3: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, 2020 at 8: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 (stackoverflow.com/questions/1082095/…)
    – crazy_code
    Apr 11, 2020 at 9: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, 2020 at 9:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy