Search code examples
javahibernateequalshashcodeeffective-java

Using auto generated id of Hibernate entity object in the equals and hashcode methods


Lovely equals and hashcode, all the theory is here and also here

I have taken the decision to use the auto-generated id within equals() and hashcode() in a number of my hibernate entity/domain objects.

However, a number of websites say you should never do this due to the risk of persisting an object to the database for the first time whilst it is in the process of being compared or using hashcode.

My point of view is that in most use cases this is much more unlikely than any other field being changed.

The individual domain objects have the id generated once when they are first created, whereas nearly every other field has the opportunity to be altered during normal business processes (even a unique username can be changed ... ).

And in many of my domain objects the unique id is pretty much the only suitable field to be considered (Person, Address, Pet, ... Customer etc etc ? Combining fields is a good idea, but never using the auto generated id is, I think, not good advice.

Am I missing something else ?


Solution

  • You should read Equals and HashCode on the Hibernate Community Wiki.

    The main reason for not using the database identifier in equals, and by implication, hashCode is for dealing with stored, but not persisted, entities. Prior to persistence all you instances are going to be equal, unless you take care to handle that case explicitly.

    If you know that you're not going to be in this scenario, and you make sure it's well documented, you may well be OK. You can always change the implementations later.