I have struggled to get a good way to relate a Role entity to my User entity in Java Hibernate. I have a User entity which has a List of Role entities. I want to relate them so if a User is deleted all the Role entities which have that User are also deleted with a cascade or the like.
I started off with a @OneToMany (User) & ManyToOne (Role) relationship between the two entities, but when I delete the User it just set the column which contained the user in the role table to NULL. It was then suggested the relationship was @ManyToMany however this caused Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements which I have yet to successfully resolve. Hence I ask what is the best way to achieve the desired relationship between the User and Role before i go too far down the rabbit hole.
Please note: In this example the Role is more of a permission, so users can have the same permission but they are linked to the username. In the table below you can see digby.tyson has the same role as reed.robert no. 7, but if digby was deleted then the role on reed should remain
User.java
@SerializedName("userrole")
@Expose
// @OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Role> userRoles = new ArrayList<Role>();
Role.java
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private RoleEnum role;
// @ManyToMany / @ManyToOne
@JoinColumn(name = "user")
private User user;
[Getters & Setters]
Sample Table
+----+------+------------------------+
| id | role | user |
+----+------+------------------------+
| 1 | 0 | digby.tyson@gmail.com |
| 2 | 1 | digby.tyson@gmail.com |
| 3 | 2 | digby.tyson@gmail.com |
| 4 | 3 | digby.tyson@gmail.com |
| 5 | 4 | digby.tyson@gmail.com |
| 6 | 5 | digby.tyson@gmail.com |
| 7 | 6 | digby.tyson@gmail.com |
| 8 | 7 | digby.tyson@gmail.com |
| 9 | 5 | ronny.polley@gmail.com |
| 10 | 6 | ronny.polley@gmail.com |
| 11 | 7 | reed.robert@gmail.com |
+----+------+------------------------+
Thanks for any feedback, I have tried to solve this issue for over a day, so it would be much appreciated.