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

前端 未结 2 1672
旧时难觅i
旧时难觅i 2020-12-07 05:24

Someone can please suggest me how I can do equals and hashCode methods of these entities?

This is a many-to-many relationship between a Gara (Contest) and Agenzia (A

相关标签:
2条回答
  • 2020-12-07 06:00

    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.

    0 讨论(0)
  • 2020-12-07 06:21

    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;
    }   
    
    0 讨论(0)
提交回复
热议问题