ColdDeath
ColdDeath

Reputation: 49

Equals Verifier fails with error related to hashcode check for JPA entity

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:

  1. https://thorben-janssen.com/ultimate-guide-to-implementing-equals-and-hashcode-with-hibernate/
  2. 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?

Upvotes: 1

Views: 764

Answers (1)

jqno
jqno

Reputation: 15520

Disclaimer: I'm the creator and maintainer of EqualsVerifier.

You have to .suppress(Warning.STRICT_HASHCODE) in this case, because EqualsVerifier doesn't recognise this by default.

I'm aware of the best practices you cite, and I've considered enforcing them in EqualsVerifier, but I decided against it for now.

Upvotes: 2

Related Questions