How do you handle object equality for java objects managed by hibernate? In the \'hibernate in action\' book they say that one should favor business keys over surrogate keys
I use to do it that way: equal and hashcode use the key when it has been set, otherwise equals uses the base implementation (aka ==). It should work too if hashcode() returns super.hashcode() instead of 0.
@Override
public int hashCode() {
if (code == null) {
return 0;
} else {
return code.hashCode();
}
}
@Override
public boolean equals(Object obj) {
if (obj instanceof PersistentObject && Hibernate.getClass(obj).equals(Hibernate.getClass(this))) {
PersistentObject po = (PersistentObject) obj;
if (code == null) {
return po.code == null && this == po;
} else {
return code.equals(po.getCode());
}
} else {
return super.equals(obj);
}
}