I have a simple class Role:
@Entity
@Table (name = "ROLE")
public class Role implements Serializable {
@Id
@GeneratedValue
private Integer id;
@Column
private String roleName;
public Role () { }
public Role (String roleName) {
this.roleName = roleName;
}
public void setId (Integer id) {
this.id = id;
}
public Integer getId () {
return id;
}
public void setRoleName (String roleName) {
this.roleName = roleName;
}
public String getRoleName () {
return roleName;
}
}
Now I want to override its methods equals and hashCode. My first suggestion is:
public boolean equals (Object obj) {
if (obj instanceof Role) {
return ((Role)obj).getRoleName ().equals (roleName);
}
return false;
}
public int hashCode () {
return id;
}
But when I create new Role object, its id is null. That’s why I have some problem with hashCode method implementation. Now I can simply return roleName.hashCode () but what if roleName is not necessary field? I’m almost sure that it’s not so difficult to make up more complicated example which can’t be solved by returning hashCode of one of its fields.
So I’d like to see some links to related discussions or to hear your experience of solving this problem. Thanks!
Bauer and King’s book Java Persistence with Hibernate advises against using the key field for equals and hashCode. They advise you should pick out what would be the object’s business key fields (if there was no artificial key) and use those to test equality. So in this case if role name was not a necessary field you would find the fields that were necessary and use them in combination. In the case of the code you post where rolename is all you have besides the id, rolename would be what I’d go with.
Here’s a quote from page 398:
An easy way I use to construct an equals and hashcode method is to create a toString method that returns the values of the ‘business key’ fields, then use that in the equals() and hashCode() methods. CLARIFICATION: This is a lazy approach for when I am not concerned about performance (for instance, in rinky-dink internal webapps), if performance is expected to be an issue then write the methods yourself or use your IDE’s code generation facilities.