Pitfalls of Lombok — Efficient way to use EqualsAndHashCode in the entity class

Dinakaran Ramadurai
2 min readJan 14, 2023

--

Pitfalls of Lombok — Efficient way to use @EqualsAndHashCode in the entity class

It is a typical day in a developer’s life to copy and paste from the internet. Consider two entity classes — Tweet and Comment with a one-to-many relationship between Tweet and Comment. Most of the developers will annotate their entity class with @EqualsAndHashCode of Lombok without knowing the actual need for it. In entity class, the hashcode() method should always return the fixed value of something like 100, and the equals() method should compare only the type of object, primary key equality with the null check as shown below.

Custom implementation of equals and hashcode

If you don't want to implement it you can annotate with @EqualsAndHashCode of Lombok like below

using Lombok's EqualsAndHashCode

So Lombok will generate equals() and hashcode() methods for us as shown below

equals and hashcode generated classes of Lombok

If you closely observe these two methods we can able to find multiple issues. The first one is Lombok including all the non-final methods in equals() and hashcode() calculation which is not required. we know that in entity class two objects will be equal if their primary key is equal. This will increase the overhead of equals() and hashcode() methods.

You can change that by setting the onlyExplicitlyIncluded attribute of the @EqualsAndHashCode annotation to true and annotating the primary key attribute with @EqualsAndHashCode.Include as shown below.

using onlyExplicitlyIncluded feature of Lombok

Now Lombok will generate equals() and hashcode() methods with the id field alone as shown below.

generated class of lombok with only primary key included

Now you might think this might solved the issue, but it's not. This equals() method will return true if the primary key of both objects is null which shouldn’t happen. The equals() method should always return false for two objects with null as the primary key. Because of this issue, you cannot add two new entity objects to the set

Conclusion

.That implies you cannot add two new Comments to the Tweet entity. Thus you should avoid using the @EqualsAndHashCode of Lombok.

--

--

Dinakaran Ramadurai
Dinakaran Ramadurai

Written by Dinakaran Ramadurai

Software Engineer who solves problems and helping others with same problem

No responses yet