Given we have such class:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class User {
@Id
private Long id;
private String name;
private Integer age;
@Override
public final boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User user)) return false;
return Objects.equals(id, user.id);
}
@Override
public final int hashCode() {
return getClass().hashCode();
}
}
When I test it via EqualsVerifier (https://jqno.nl/equalsverifier/) I get an error:
java.lang.AssertionError: EqualsVerifier found a problem in class com.example.model.User.
-> Significant fields: equals relies on id, but hashCode does not.
com.example.model.User@e11ecfa has hashCode 236055802
com.example.model.User@e11ecfa has hashCode 236055802
Why I getting this error while using constant in hashcode is a best practice according to:
- https://thorben-janssen.com/ultimate-guide-to-implementing-equals-and-hashcode-with-hibernate/
- https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
Yes, I can suppress this error by .suppress(Warning.STRICT_HASHCODE) option. But looks like this behaviour should be used by EqualsVerifier by default. Or maybe I'm wrong?