vladmihalcea / hypersistence-optimizer

Hypersistence Optimizer allows you to get the most out of JPA and Hibernate. By scanning your application configuration and mappings, Hypersistence Optimizer can tell you what changes you need to do to speed up your data access layer.
https://vladmihalcea.com/hypersistence-optimizer/
Apache License 2.0
306 stars 43 forks source link

EqualsHashCodeEvent warning when using spring AbstractPersistable #198

Closed willome closed 1 year ago

willome commented 1 year ago

My entity is extending spring AbstractPersistable but I have a MAJOR - EqualsHashCodeEvent warning. Maybe AbstractPersistable is not fully compliant and we should make some changes in the spring data code. I even have tried to extends this class with no sucess:

       @Override
    public int hashCode() {
        return Objects.hash(getId());
    }

    @Override
    public boolean equals(Object obj) {
        if (null == obj) {
            return false;
        }
        if (this == obj) {
            return true;
        }
        if (!getClass().equals(ProxyUtils.getUserClass(obj))) {
            return false;
        }
        AbstractPersistable<?> that = (AbstractPersistable<?>) obj;
        return Objects.equals(getId(), that.getId());
    }

any ideas ?

Guillaume

vladmihalcea commented 1 year ago

@willome As I explained in this article, using the id in the hashCode method is not going to render consistent results when changing the entity from one state to another.

If this is the AbstractPersistable implementation, then it's wrong.

The AbstractPersistable should define the equals and hashCode methods like this:

@Override
public boolean equals(Object o) {
    if (this == o) return true;

    if (!(o instanceof AbstractPersistable))
        return false;

    AbstractPersistable other = (AbstractPersistable) o;

    return id != null &&
           id.equals(other.getId());
}

@Override
public int hashCode() {
    return getClass().hashCode();
}
willome commented 1 year ago

Oh I misread the hashCode problem. Thanks.