Hello,
Here is an implementation of equals and hashCode that
passes successfully the 3 tests listed above in the article:
- "multiple new instances in set"
- "equal to same object from other session"
- "collections intact after saving"
I did not test it against the "use in a composite-id" test.
The principle is simple:
The first time equals or hashCode is called, we check if the
primary key (here getUserId()) is present or not.
If yes: we use it in equals/hashcode
If no: we use a UID (here _uidInEquals) during the entire life of this
instance
even when latter on this instance is assigned a primary key.
I'd be happy to get some feedbacks on this implementation (is it
acceptable or not ?)
<code>
private boolean _freezeUseUidInEquals = false;
private boolean _useUidInEquals = true;
private java.rmi.dgc.VMID _uidInEquals = null;
private void setEqualsAndHashcodeStrategy() {
if (_freezeUseUidInEquals == false) {
_freezeUseUidInEquals = true;
_useUidInEquals = (getUserId() == null);
if (_useUidInEquals) {
_uidInEquals = new java.rmi.dgc.VMID();
}
}
}
public boolean equals(Object object) {
if (this == object) {
return true;
}
if((object == null) || (object.getClass() != this.getClass())) {
return false;
}
UserModel other = (UserModel) object;
setEqualsAndHashcodeStrategy();
if (_useUidInEquals) {
return _uidInEquals.equals(other._uidInEquals);
} else {
return getUserId().equals(other.getUserId());
}
}
public int hashCode() {
setEqualsAndHashcodeStrategy();
if (_useUidInEquals) {
return _uidInEquals.hashCode();
} else {
return getUserId().hashCode();
}
}
</code> |