For equals and hashcode or not in entity classes, this is a question

I am trying to discuss how best to deal with the practice of implementing hash code and equality for entities (I mean an object in a general sense, but in most cases it will be a JPA entity).

Chapter 24 of the Hibernate Guide http://docs.jboss.org/hibernate/core/3.3/reference/en/html/best-practices.html talks about this ...

Define natural keys for all objects and match them with. Add equal () and hashCode () to compare the properties that make up the natural key.

It makes sense to have .equals and .hashcode include only these natural keys, but what if you have more than one instance of the same object (the same natural id, thus the same hashcode)? It seems like this practice can have subtle consequences elsewhere in your application. Has anyone tried this before on a large scale?

+6
equals hashcode hibernate jpa entity
source share
2 answers

Sometimes you want Equals to compare all the properties and the time when you want Equals to be the only key. We had much more success using helper classes that are explicit, so there is no ambiguity about what is being compared.

ByKeyComparer.Equals... ByPropertiesComparer.Equals... 

or

 Entity1.EqualsByKey... Entity1.EqualsByProperties... 
+3
source share

I tried this before on a large scale (or at least in an application that uses hibernate heavily). This is a good idea.

It makes sense to have .equals and .hashcode include only these natural keys, but what if you have more than one instance of the same object (the same natural id, thus the same hashcode)? It seems that this practice may have minor effects elsewhere in your application.

This is what it is intended for. Usually, you want to compare multiple instances of the same object when comparing .equals, and yes, this has consequences elsewhere. IMO is that everything will work as expected.

+6
source share

All Articles