IMO you definitely want to avoid any lazily-loaded property as part of
equals/hashcode.

There was an interesting thread on the Hibernate forums on the topic of
equals / hashCode: http://forum.hibernate.org/viewtopic.php?t=928172

The larger point is how do you define object identity. The Hibernate folks
recommend separating the object id and the business key (see here for more:
http://www.hibernate.org/109.html)

I'm not crazy about the business key examples I've seen on the Hibernate
docs / forum (e.g., make a person's email address the business key. Well, we
all know that email addresses occasionally change.). So one approach I've
thought about is the following:

1) assign a UUID at object creation time (maybe using something like this
http://jug.safehaus.org/),
2) make it a property of the object with getter & setter, and store it in
the db as a regular column, and have a separate, surrogate primary key.
3) use only the UUID in hashCode / equals.

That way you get rid of the possibility that anything used in hashCode /
equals is not loaded, or might change during the object's life.

Jason



On 2/14/07, Michael Horwitz <[EMAIL PROTECTED]> wrote:

Hi Ron,

From my experience with Hibernate I would be extremely cautious of using
too many fields in the equals/hashcode of persisted entities (particularly
the latter). One specific problem I came accross was that when building a
collection of persisted entities, Hibernate adds empty elements to the
collection before populating their fields. This is extremely problematic
when working with sets, as it means that the objects hashcode can change
after it has been added to the set. We resorted to making the hashcodes of
persisted objects a fixed integer. Not very efficient, but it worked!

I am guessing here, but I would imagine that in your case Hibernate is
trying to get the object's hashcode before it goes about populating the lazy
collection. So not really related to the filter, but more to do with the
internal workings of Hibernate.

Mike

On 2/14/07, Ron Anderson <[EMAIL PROTECTED]> wrote:
>
>  Hi All,
>
> I've been wondering about this for awhile and especially when I forget
> about it and scratch my head when it happens.  Hoping someone can shed some
> light.
>
> I use commonclipse for generating the equals, hashCode and toString
> methods automatically at the bottom of my pojo's.  I've noticed that when
> you leave a collection in this autogenerated set of methods that you can end
> up with a 'Yikes' that says illegal access to lazy collection' when you try
> to view the forms.  It looks like the OpenSessionInView filter doesn't work
> or something else is going on.
>
> Any downsides to leaving collections out of the commonclipse generated
> methods?  Does anyone know why this happens?
>
> cheers and thanks in advance for any help,
>
> Ron
>


Reply via email to