I need help to save several roles of a user to database. Using Spring Boot JPA. User can have many roles. A role belongs to one user. I tried to create three users - an admin, a user and a manager. Admin has admin role, user has user role. Manager has both - admin and user roles.
I have Authority class that has a role. The problem is that for the manager hibernate creates only last role - USER. And I expected that it will have both roles. In database I see that manager has only 1 row. And it should have 2 rows. What am I doing wrong?
User:
@Entity
@Table(uniqueConstraints= {@UniqueConstraint(columnNames="username")}, name = "Users")
public class User implements UserDetails{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NonNull
private String username;
@NonNull
private String password;
@NonNull
private String email;
@OneToMany(mappedBy = "user")
private List<Authority> authorities = new ArrayList<>();
//...
Authority:
@Entity
public class Authority implements GrantedAuthority {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Enumerated(EnumType.STRING)
private Role authority;
@JsonIgnore
@ManyToOne(optional = false)
private User user;
//...