|
From: <jue...@we...> - 2003-07-29 14:03:39
|
Everyone, A rather general problem that I've been wondering about for a while: = "equals"/"hashCode" implementation for entities with an externally = determined ID. I've repeatedly discovered issues with primary-key-based implementations = of the both. The root cause is adding an entity to a HashSet *before* = setting its ID, e.g. when using a MySQL autoincrement column as primary = key with Hibernate. Example: Filling a parent folder including some = children and then saving them all in one go. A "contains" or "remove" = call on the children collection will fail then, as the hash code has = changed while the object was in the collection. Of course, HashSet states that this is illegal, but how to avoid this? = It's especially tricky with m:n associations, e.g. between parents and = children. No matter how you load such an object tree, some entities will = always get added to a collection in a not fully initialized state, = potentially incurring hash code failure when the ID hasn't been set yet. = This not only arises with persistence tools like Hibernate but also with = remoting tools like Hessian. I see various solutions for the problem: - Reinitializing the HashSet after the change: This solves the = create-then-save issue, but seems like a hack and doesn't address the = mutual m:n issue. - Use the standard "equals"/"hashCode" implementations: This solves both = issues, but object equality is based on object identity then, which = isn't suitable e.g. for web applications that might store one entity in = the HTTP session and load another freshly, maybe wanting to compare = their parent. - "equals" based on the primary key, but "hashCode" returning the same = value for all instances of a class: This is valid, as "hashCode" has to = return the same value if "equals" is true but just *should* return = distinct values if not equal. As "hashCode" doesn't depend on the = primary key anymore, both issues are solved. The latter has the disadvantage that it doesn't care for the performance = of hash lookups. Looking up such an entity in a hash table is linear = like with an unsorted array. But typically this isn't a big deal, as = most collections will just contain a limited number of objects anyway, = e.g. assocation collections in an object tree. We've currently adopted the latter approach, but I'm not 100% convinced = that there isn't a better solution for the problem. What do you think? Juergen DI J=FCrgen H=F6ller Senior System Architect ______________________________________ werk3ATS - division systementwicklung part of werk3AT internetmedien oeg europaplatz 4 A - 4020 linz t. +43 (0) 732 71 65 29 502 f. +43 (0) 732 71 65 29 3 jue...@we... www.werk3at.com ______________________________________ werk3ATS - WIR ENTWICKELN ERFOLG |