Over a million developers have joined DZone.

Tread Carefully With Entities Equality

· Java Zone

Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems, brought to you in partnership with AppDynamics.

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

The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}