The background to this question is the following:
Hash code for expandable class (future proof)
However, I should mention why I would like to know this.
I have a class with many roles (boolean fields). I don’t want to make named queries (JPA) like
@NamedQuery(name= "searchUserWithRoles", query="SELECT u FROM User u WHERE u.role.admin = :admin AND u.role.printer = :printer AND ... .. . .+ 20 more booleans...)
My idea was to make a hashcode (or similar) for all fields in the Role class which reduce the named query to:
@NamedQuery(name= "searchUserWithRoles", query="SELECT u FROM User u WHERE u.role.hashcode = :hashcode)
I think (but I am not sure) that this will increase the performance, but also make my queries very short (I have a more “Role” like fields in my user class).
Also, when I update the Role class with more roles fields I do not need to update the named queries.
So that is the background to the first question.
The new question is: Is there some way to generate a “hashcode like” field in the Role class that is a description of all fields that is true (even if the Role class is updated with more fields)?
Thanks in advance
It sounds like you don’t need a “hash code” – you just need a bit mask. So long as you have 32 fields or fewer, you can store this in a 32-bit integer. If you have 64 fields or fewer, you can store this in a 64-bit integer.
Each field would then have one bit dedicated to it – so admin could be bit 0 (value 1), printer could be bit 1 (value 2), then next field would be bit 2 (value 4) etc. Just add together the values (effectively a bitwise OR).
Then to query for any particular combination, you’d just use a bitwise AND between the data and a “mask” with only the relevant bits set. So if you wanted to find every admin who didn’t have printer rights, you’d check for
value & 3 == 1.Note that all of this may well interfere with any indexing the database would want to do, and the database may well optimize in this sort of way anyway. Do you have any evidence that storing them as separate fields – keeping your representation closer to your logical data structure – actually causes a problem?