Enterprise ApplicationDevelopment with Ext JSand Spring
上QQ阅读APP看书,第一时间看更新

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:

Refactoring Java equals() and hashCode()

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:

Refactoring Java equals() and hashCode()

From the pop-up menu, select the equals()… option and ensure that the idCompany : Integer field is selected in the Generate equals() pop up:

Refactoring Java equals() and hashCode()

Click on Generate to create the new equals method:

Refactoring Java equals() and hashCode()

Click on the information icon (circled) over line 92 to display the context information:

Refactoring Java equals() and hashCode()

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:

Note

Returns true if the arguments are equal to each other and false otherwise. Consequently, if both the arguments are null, true is returned, and if exactly one argument is null, false is returned. Otherwise, the equality is determined using the equals method of the first argument.

You can now replace the autogenerated equals method of the Project, Task, User, and TaskLog entity classes in a similar way.