Hibernate + fetch=FetchType.LAZY making trouble

Now, for the third time, I’ve run into some weird and wonderful situation where a lazy object wasn’t initialized when I was using it.  When will I learn?  Don’t use FetchType.LAZY unless you’re really know what you’re doing, and test carefully afterwards.  The precise problem I seem to be having is that my hashCode() and equals() methods don’t work.  Anyway, a word of caution!


3 Responses to Hibernate + fetch=FetchType.LAZY making trouble

  1. Are you sure you did not close or clear the session or transaction before try to navigate your lazy object ? This is usually the typical trouble with lazy objects I also encountered with when first using HIbernate. In case of pure EJB (JPA), you can get the same behavior when returning lazy object as a result of EJB bean method.

  2. dobes says:

    Yeah, I’m in a transaction – it’s one EJB using another one. I’m using reflection to fetch properties of an entity and comparing them using equals() and, for whatever reason, equals() returned false when I compared an object to itself! Weird!

    During debugging, I saw that the object was a lazy proxy, and that it was not loaded, so I changed FetchType.LAZY to FetchType.EAGER and suddenly it worked!

    I made sure my equals() method wasn’t accessing members directly – it was using getter methods. So, I have no idea why this was not working this way.

    Some kind of issue with accessing members with reflection? Or something else?

    I guess I just don’t feel like I have time to debug these weird hibernate behaviors when I can just not use lazy fields.

    After making this post, though, I did switch some of my inverse relationships back to LAZY because they were causing all kinds of extra things to be fetched that I didn’t need… hopefully I won’t get burned by that too soon.

  3. There are 2 possible solutions.

    Choose for the opensessioninview-pattern.
    Manually initialize collections in dao-calls, where you need them: Hibernate.initialize(…)

    Eager fetching by default is the root of all evil.

%d bloggers like this: