equals and hashCode of these entities (Spring MVC + Hibernate)

痞子三分冷 提交于 2019-11-28 02:20:31

These seem to work well. I post hoping someone will find it useful:

GaraAgenzia class:

public boolean equals(Object o) {
        if (this== o) return true;
        if (o ==null|| getClass() != o.getClass()) return false;

        GaraAgenzia that = (GaraAgenzia) o;

        if (getPk() !=null?!getPk().equals(that.getPk()) : that.getPk() !=null) return false;

        return true;
    }

    public int hashCode() {
        return (getPk() !=null? getPk().hashCode() : 0);
    }   

GaraAgenziaId class:

public boolean equals(Object o) {
    if (this== o) return true;
    if (o ==null|| getClass() != o.getClass()) return false;

    GaraAgenziaId that = (GaraAgenziaId) o;

    if (gara !=null?!gara.equals(that.gara) : that.gara !=null) return false;
    if (agenzia !=null?!agenzia.equals(that.agenzia) : that.agenzia !=null)
        return false;

    return true;
}

public int hashCode() {
    int result;
    result = (agenzia !=null? agenzia.hashCode() : 0);
    result =31* result + (gara !=null? gara.hashCode() : 0);
    return result;
}   

It is not an exactly answer, but may help someone in a similar problem. I made a abstract class that is extended by all the entities. This way I don't need to implement these methods in all entities.

    public abstract class GenericEntity implements Serializable{

    protected static final long serialVersionUID = 1L;

    abstract public Serializable getId();

    @Override
    public int hashCode()
    {
        return (getId() == null) ? System.identityHashCode(this) : getId().hashCode();
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (this.getClass() != obj.getClass())
            return false;
        if (org.hibernate.Hibernate.getClass(this) != org.hibernate.Hibernate.getClass(obj))
            return false;
        GenericEntity other = (GenericEntity) obj;
        if (getId() == null || other.getId() == null)
            return false;
        return getId().equals(other.getId());
    }

}

I think in your case you could put it in your BaseEntity.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!