I have an @Entity-annotated Model class in my Play application, which I am stuffing into a Set to ensure uniqueness prior to saving to the database. Since the objects haven’t been saved yet, they don’t have a key value. So the comparison must be based on their properties.
I took a peek at the equals() implementation in JPABase, and it seems to explicitly make all entity objects unequal if they don’t have a key yet.
So, my question(s):
- Is it okay to implement
equals()andhashCode()in myModelsubclasses? - If so, what is the best/correct way to do so? Should I call
super.equals(), and how should I deal with the result?
I don’t recommend to implement
equalsorhashCodein application model class. The uniqueness should be ensured by database in the end. From the application’s perspective, uniqueness is almost always imposed on a certain field, e.g. username or email etc. I’ve never met the case that data entity uniqueness is computed on the entire object viahashCodeorequalsmethod.