Skip to content

JPA Entity check requires all fields to be used in hashCode #853

@sithmein

Description

@sithmein

We have JPA entities which don't use all properties in the hashCode implementation. Instead we rely on the unique ID only. Therefore we already had enabled suppress(Warning.STRICT_HASHCODE) in the past. However, the new JPA entity check seems to require that all properties are used in the hashCode implementation. If a property is not used you get a (false) error such as

-> JPA Entity: direct reference to field links used in hashCode instead of getter getLinks.

In fact neither the field nor the getter are used (on purpose).

The following code shows the problem:

import java.util.Collection;
import java.util.Objects;

import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.Test;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.OneToMany;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;

class JPATest {
    @Entity
    public static class Ent {
        @Column(name = "id")
        String id;

        @OneToMany(fetch = FetchType.LAZY)
        Collection<String> links;

        public String getId() {
            return id;
        }

        public Collection<String> getLinks() {
            return links;
        }

        @Override
        public int hashCode() {
            return id.hashCode(); // id only on purpose
        }

        @Override
        public boolean equals(final @Nullable Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            Ent other = (Ent)obj;
            return Objects.equals(id, other.id) && Objects.equals(getLinks(), other.getLinks());
        }
    }

    @Test
    void test() {
        EqualsVerifier.forClass(Ent.class)
            .usingGetClass()
            .suppress(Warning.STRICT_HASHCODE)
            .verify();
    }
}

The expected behaviour is that this test passes but instead it fails with the above error message.

I tested with version 3.15.1.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions