I'm leery of rekindling
the long-running debate about equals and hashCode, but I have a case that doesn't seem to be addressed there or in the
Equals and HashCode treatise.
1. I have an entity (class 'A'), which owns a set of composite elements (class 'B').
2. I'm never comparing the composite elements across sessions.
3. The default (Object) implementation of equals and hashCode seem to be sufficient for my domain model's semantics.
4. Whenever I load the entity (in a fresh session), make no mods and then commit, Hibernate judges the set dirty (even when it contains a single element) and issues a DELETE and re-INSERT for the element.
Is this expected behavior?
Early in the equals/hashCode thread, I read:
melquiades:
Quote:
On (1): What's wrong with instance-based equality? Doesn't Hibernate guarantee instance uniqueness within a session? (It had darned well better!) Does this break caches, or what? This should, in theory, be a perfectly valid approach.
michael (Hibernate Team):
Quote:
Theoretically nothing, Hibernate sure does not have a problem with that. You must remeber however that in this case two equal objects are not .equals() if loaded in different sessions
From this I take it that what I'm seeing is
unexpected behavior, since I'm not comparing anything across sessions.
Incidentally, this was reported in
HHH-1690, where the reporter was referred to
7.2. Collections of dependent objects, where it says:
Quote:
Note: if you define a Set of composite elements, it is very important to implement equals() and hashCode() correctly.
I take Michael's comment to mean that instance-based equality may be "correct" for some applications.
Anyways.. long post, but I'm trying to be thorough. The
one question I really want answered is whether the behavior I'm seeing in Hibernate 3.1.3 is expected behavior.