Java JPA enum-like String options

Viewed 63

I am trying to implement a simple User-Roles relationship in a Spring application, for security. The basic entities (some fields and annotations trimmed):

User

@Table(name="usr")
public class User implements Serializable {
  @Id
  private UUID id;
  @ManyToMany(fetch=FetchType.EAGER)
  @JoinTable(name="user_roles", joinColumns=@JoinColumn(name="user_id", referencedColumnName="id"),
    inverseJoinColumns=@JoinColumn(name="role_id", referencedColumnName="id"))
  private Collection<Role> roles;
}

Role

public class Role implements Serializable {
  @Id
  private UUID id;
  @ManyToMany(mappedBy="roles")
  private Collection<User> users;
  private String name;
}

So far, so good. However, I also have a class that defines a list of role-name values:

UserRoles

public class UserRole {
 public static final String ADMIN = "admin";
 public static final String USER = "user";
}

I want to constrain the values of the Role's name field to the values in UserRoles, effectively like an enum.

These role values will get used within Spring Security functions that require roles to be string values. As such, if I were to make UserRoles an enum, any database storage would be of ints – the ordinal definition position within UserRoles – which would force me to keep any potentially deprecated options, and also require a hacky conversion every time I need to convert the role to a string that can be passed around in a JWT, etc. (If I want to look at my database directly, it will also be far less informative.)

Is there some way to define Role's name field as limited to the static values in UserRoles? (Changing how or where these values are stored is entirely acceptable.)

1 Answers

You can define like this

public enum UserRoleEnum {
  USER, ADMIN
}

And in entity

@Enumerated(EnumType.ORDINAL)
private UserRoleEnum role;
Related