I'm using
<composite-id>.
In hibernate doc:
Your persistent class must override equals() and hashCode() to implement composite identifier equality.
So I implement my own equals() and hashCode() with composit-id.
like this:
Code:
public int hashCode() {
return getOID().hashCode(); //getOID() maybe return null;
}
I want to assign id when hibernate calling onSaveOrUpdate(SaveOrUpdateEvent event) method.
Code:
@Override
public Serializable onSaveOrUpdate(SaveOrUpdateEvent event)
throws HibernateException {
if (event.getObject() instanceof AbstractEDO) {
AbstractEDO edo = (AbstractEDO)event.getObject();
if (edo.getOID() == null) {
OID oid = new OID();
oid.setUid(UIDGenerator.nextID());
oid.setQName(edo.getRecordType().getQualifiedName());
oid.setAccountId(UserContext.getAccountID());
edo.setOID(oid);
}
}
return super.onSaveOrUpdate(event);
}
The problem is :
I add a POJO instance to a HashSet,it will throw NPE.
Because I do not assign id until call onSaveOrUpdate() method.
Resolution:
1. Assign id when calling getOID().But I want to run some test cases in no database entironment.
If I assign id in getOID() method,will cause other problem. Because generate OID need to connect database to get next id.
2. Do not override equals() and hashCode() ,but hibernate doc require to override.
3. Changed hashCode() method like this:
Code:
public int hashCode() {
return getOID() == null ? 0 : getOID().hashCode();
}
but the hash code is not constant.
Is there a better way ?Any help greatly appreciated.
Regards
Wesley