I agree with @S.P.Floyd as well. But I wanted to add something more.
There are situations when an entity doesn't have unique business properties. For instance, an entity may only have A
(the PK) and B
(a business property), but many entities have the same B
value.
In this case, it is difficult to create an equals()
and hashcode()
. You certainly do not want to base them on A
, as you won't be able to compare a persisted object with one that hasn't been persisted yet. And you can't base it on B
alone, because then many objects that are different unique entities would appear to be the same.
What I do in these situations is have a Date created = new Date();
property. When an entity is created, it automatically gets a created timestamp. In my equals()
and hashcode()
I include both B
and created
. This isn't perfect, as there is a very slim chance that two objects could be created at the same time (especially in a clustered solution), but it's a start. If you must, add a UID or other generated business property that isn't the database's PK.