Answer the question
In order to leave comments, you need to log in
What is the best annotation to use for roles (for Hibernate) in Spring?
Here, for example, I have
@Enumerated(EnumType.STRING)
@ElementCollection(fetch = FetchType.EAGER)
private Set<Role> roles;r>
Answer the question
In order to leave comments, you need to log in
Good afternoon.
I usually do it the other way.
1) I create enum UserRole, UserPrivilege
2) I create entity Role. If necessary, you can also add a set of Privilege for each role
3) Further, each entity contains a role or a set of roles.
4) I connect the User entity with the UserRole entity
Here are the sources:
The User entity
@Entity
@Data
@Table(name = "users")
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class User {
//...
@JsonBackReference
@ToString.Exclude
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "users_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
}
@Entity
@Data
@EqualsAndHashCode(callSuper = false)
@Table(name = "roles")
public class Role implements GrantedAuthority {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long roleId;
@JsonBackReference
@ToString.Exclude
@ManyToMany(mappedBy = "roles")
private Collection<User> users;
@JsonBackReference
@ToString.Exclude
@ManyToMany
@JoinTable(
name = "roles_privileges",
joinColumns = @JoinColumn(name = "role_id"),
inverseJoinColumns = @JoinColumn(name = "privilege_id"))
private Collection<Privilege> privileges;
@Enumerated(EnumType.STRING)
private UserRole name;
public Role() {
super();
}
public Role(UserRole name) {
super();
this.name = name;
}
@Override
public String getAuthority() {
return name.name();
}
}
public enum UserRole {
USER,
ADMIN
}
@Entity
@Data
@EqualsAndHashCode(callSuper = false)
@Table(name = "privileges")
public class Privilege {
@Enumerated(EnumType.STRING)
private UserPrivilege name;
@JsonBackReference
@ToString.Exclude
@ManyToMany(mappedBy = "privileges")
private Collection<Role> roles;
}
public enum UserPrivilege {
ADMIN_PRIVILEGE,
READ_PRIVILEGE,
WRITING_COMMENTS_PRIVILEGE
}
I'm generally zero in Java, but when I dabbled with Spring, the articles on this site helped a lot.
https://www.baeldung.com/role-and-privilege-for-sp...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question