Tread carefully with entities equality

I’ve barely begun Scala and I learned plenty of facts on Java (see previous article on a javac compiler quirk). Now, I’ve come upon another interesting point, this time completely unrelated to the compiler. It’s strange because now that I’ve realized it exists, it makes me nervous on how I could have ignored it before.

The core of the problem lies in mutable objects. IMHO, entities should be mutable because one can load one from the datastore, change it, then save changes back to the store.

In order to reveal it, let’s create a simple entity:

public class Person {
  private Long id;
  private String name;
  // Getters and setters
  ...
}

Now, imagine the following entity:

public class Registry {
  private Long id;
  private Set<Person> persons;
  // Getters and setters
  ...
}

Since we created a Set of persons, we have to both implement equals() and hashCode() for the Person class. Using our favorite IDE, we confidently generate both from the id and name attributes for a person should be equals to another only when all attributes are the same. Let’s test this behaviour:

Person person1 = new Person();
person1.setId(1L);
person1.setName("Joe");
Person person2 = new Person();
person2.setId(2L);
person2.setName("Jack");
Set<Person> persons = new HashSet<Person>();
persons.add(person1);
persons.add(person2);
person1.setName("William");
persons.add(person1);

Now guess the set’s size. Bad (but common) answer: 2. Good answer: 3. The reason is that setting the name changed `person1’s hash code, thus the set contains it twice.

For mutable objects, and more particularly entities, only ids (primary keys) should be accounted for when generating equals() and hashCode().

This may seem a simple advice but it will transform into a deadly bug if not headed. Unfortunately, this bug can lay dormant for some time if you design your entities collections with List (ordered collections) instead of Set: the former won’t call hashCode() nor equals().

To be sure, try to design your objects to be immutable (which probably won’t be the case for entities).

Sources for this article are available here in Maven/Eclipse format.

Nicolas Fränkel

Nicolas Fränkel

Developer Advocate with 15+ years experience consulting for many different customers, in a wide range of contexts (such as telecoms, banking, insurances, large retail and public sector). Usually working on Java/Java EE and Spring technologies, but with focused interests like Rich Internet Applications, Testing, CI/CD and DevOps. Also double as a trainer and triples as a book author.

Read More
Tread carefully with entities equality
Share this