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
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.
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;
}