The proper implementation of equals
and hashCode
is indeeed quite an issue for entities.
You do not have to persist an extra business key value if you have a 'natural' primary key, like a social security number for a person. It can be a single value or a combination of values - like a combination of name, surname, birthdate and address. If you have such a natural PK, please use it. If you do not have it, using UUID is a fine way to create one.
If you are using UUID for equals
and hashCode
, you should also persist it, so two instances of the same record are considered to be equal.
Your equals
and hashCode
should be based on this business key and not on the DB-provided id. If using the DB-provided id, all new entities are considered equal. This can lead to unexpected behaviour, especially when working with Collections.