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

前端 未结 2 1671
旧时难觅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.

提交回复
热议问题