Reputation: 820
It's been days I'm trying to find the correct way to implement the equals() and hashCode() methods of a composite-id class.
The trouble I'm facing when I try to update the main object (Gara) are:
My Composite-id class
@Embeddable
public class GaraAgenziaId implements Serializable {
private static final long serialVersionUID = 4934033367128755763L;
static Logger logger = LoggerFactory.getLogger(GaraAgenziaId.class);
private Gara gara;
private Agenzia agenzia;
@ManyToOne
public Gara getGara() {
return gara;
}
public void setGara(Gara gara) {
this.gara = gara;
}
@ManyToOne
public Agenzia getAgenzia() {
return agenzia;
}
public void setAgenzia(Agenzia agenzia) {
this.agenzia = agenzia;
}
@Override
public String toString() {
return "GaraAgenziaId [Gara=" + gara + ", agenzia=" + agenzia
+ "]";
}
}
Upvotes: 5
Views: 7435
Reputation: 820
these seems to work very well:
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;
}
Upvotes: 5