On our company we had an discussion on how to refer in our java source code to certain database entries.The situation is as follows:
The java web-application is connected to a MySQL Database which is setup by an SQL script, JPA/Hibernate is used for ORM. In this script we insert 3 Roles in the "roles" table (i.e. roles a user can have in a web application, i.e. the user table has a foreign key to the roles table). The roles have predefined primary keys/IDs (BIGINT) and names (VARCHAR) as given in the SQL script. The roles are not used for an security framework, but for the business logic. At the moment it looks something like this:
if(user.getRole.getId()==1) {
// user is in role A
} else if(user.getRole().getId()==2) {
// user is in role B
} ...
As the roles must be known by the source code at compile time (as the logic depends on them), we must check for user to have certain roles. The question is now how to do that. We we have discussed:
a) better checking by ID or by Name b) using String/Long constants or Enums to check for equality
to a) I would prefer checking for the ID (as it is unlikely to change as we insert the IDs at database setup with a script), the roles name are more likely to be changed during the lifetime of the application.
to b) I would prefer to use constants, as I don't like to rely on the Enums index/ordinal number. Also we don't need type safety here. The only advantage I see with enums is that its easy to fetch all values, afaik thats only possible with reflection in the case of constants. But as we have all roles defined on the DB, they could be fetched from there at runtime.
Any suggestions?