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.
If you don't want to implement it you can annotate with @EqualsAndHashCode of Lombok like below
So Lombok will generate equals() and hashcode() methods for us as shown below
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.
Now Lombok will generate equals() and hashcode() methods with the id field alone as shown below.
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.