Hm, you're right. This equals() contract may not be able to apply to hashCode().
Let's step back and look at the constraints and their implications:
[list=]An object should be equal to (and hash to the same code as) its proxy. This implies that Java == MUST NOT be the basis for equals() and hashCode() FOR PERSISTENT OBJECTS, and that persistent identity MUST be the basis for equals() and hashCode() FOR PERSISTENT OBJECTS. This will work with proxies since proxies necessarily only exist for persistent objects.
Whether an object has been persisted or not should not affect its equality or its hashcode. This implies that persistent identity MUST NOT be the basis for equals() and hashCode() for possibly-non-persistent objects, and that Java == MUST be the basis for equals() and hashCode() for possibly non-persistent objects.[/list]
This makes it pretty clear that you can't have everything you want.
Either:
1) you use Object.equals() and Object.hashCode() (i.e. Java object identity) semantics, and you give up o.equals(p);
or
2) you use persistent identity semantics, and you give up "Object newO = new O(); HashSet set = new HashSet(); set.add(newO); session.save(newO); assert(set.contains(newO));";
or
3) you change semantics as soon as you save your objects, and give up equals-immutability. (Which you also have to give up in option (2), and then you have even less consistency.)
That's it. Those are your only choices.
Way back, you asked whether Hibernate could assign object IDs on instantiation. Hibernate may not be able to enforce this itself. But you could possibly do:
Code:
public class O {
private O () {
}
public static final O create () {
O newO = new O();
ThreadLocalSession.save(newO);
return newO;
}
}
Thereby ensuring that all O's will always have been saved before you can start working with them.
The ONLY other choice would be to assign some kind of random number or other UUID on creation, which would get saved. But then you're basically doing your own ID assignment. Maybe that's what you *want* in this case...???
Personally I'm not clear on how much equals-immutability makes sense in a persistently mapped world....
Cheers,
Rob