DISQUS

DISQUS Hello! Thinking inside a bigger box is using DISQUS, a powerful comment system, to manage its comments. Learn more.

Community Page

Jump to original thread »
Author

What you didn't think you needed to know about hashCode and equals

Started by jhannes · 8 months ago

This article is a repost of my comments to the question on how to implement hashCode and equals on stackoverflow
There are some issues worth noticing if you’re implementing hashCode and equals for classes that are persisted using an Object-Relationship Mapper (ORM) like Hibernate. ... Continue reading »

5 comments

  • From a Hibernate users standpoint, could you give an example of a situation where you need to store a hashset of objects of which some are persisted, some get persisted why stored in set and some do not?

    If you declare that id shouldn't be used in hashCode; in the same way you could say that you cannot use any fields in hashCode, as every one of those can change.

    Surrogate should be the most stable property of an persist entity as it changes only once.

    Great post though, too few have been written on the subject.
  • Hi, rzei

    The example wasn't very clear. I've run into the the problem in the following situations: I have a Parent object that includes many Children in a HashSet. I construct a new Parent and add Children to it, then I persist the Parent for the first time, and the HashSet is configured persisted as well, through cascading.

    The result is that the Child objects are given an id, their hashCode change, and I can no longer find them.

    Hope this was clearer?
  • rzei raises a valid point regarding changing fields. What is your advice regarding the implementation of hashcode()? Is the only way to compute and persist some kind of unchangeable UID for each object?

    In a framework I have used, persistent keys were (wastefully) created with the object, so even if the object would never be persisted, it still had a PK. So one could use the PK in hashcode implementations.
  • I've never had much luck with the precreated keys. But then again, I use the convention of a null-key to indicate unsaved objects, so I'd run into other problems. FWIW, it sounds like your approach would behave correctly.
  • I agree that too few posts have been written on this subject. I've come into problems with equals/hashCode and persistance serveral times, but I haven't found very much useful info on the topic.

Add New Comment

Returning? Login