Refactoring Java equals() and hashCode()
Our domain layer entity classes have autogenerated equals
and hashCode
methods defined. The Company
class, for example, defines these methods as shown:
It is best practice to always provide correctly implemented equals
and hashCode
methods that use the entity ID to calculate the value that is returned. These methods are used by JPA to determine the equality between entities. Our autogenerated equals
method will work correctly with JPA as the ID entity is used in the comparison for each method. However, the //TODO: Warning
message on line 83 (see the previous screenshot) indicates an issue that can be avoided if we regenerate the equals
method with the NetBeans IDE.
Delete the equals
method and right-click on the Company.java
file in the editor using the mouse to display the context menu. Select the Insert Code… option:
From the pop-up menu, select the equals()… option and ensure that the idCompany : Integer field is selected in the Generate equals() pop up:
Click on Generate to create the new equals
method:
Click on the information icon (circled) over line 92 to display the context information:
Click on The if statement is redundant to clean your code further and replace the if
statement with the following line:
return Objects.equals(this.idCompany, other.idCompany);
The Objects
class was introduced in Java 1.7 and consists of static utility methods for operating on objects. The Objects.equals
method takes into account null
values and solves the potential //TODO: Warning
issue with the autogenerated equals
method. From the Java 1.7 JavaDoc for the Objects.equals
method:
You can now replace the autogenerated equals
method of the Project
, Task
, User
, and TaskLog
entity classes in a similar way.