Tread Carefully With Entities Equality

DZone 's Guide to

Tread Carefully With Entities Equality

· Java Zone ·
Free Resource

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();

Person person2 = new Person();

Set<Person> persons = new HashSet<Person>();




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.

From http://blog.frankel.ch/tread-carefully-with-entities-equality


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}