views:

483

answers:

3

Hi, I have a rather enormous project in which I'm trying to retrofit in-memory data. Essentially, I have a big collection of objects which contain primitives and other objects which exist in hibernate. Large sections of non-dao code rely on lazy-loading through hibernate to hydrate objects on the fly. However, since everything exists in memory, my object are not loaded, and I get hibernate lazy loading exceptions.

I could just manually implement hibernate lazy loading by dipping to hibernate and hydrating the hibernate object manually, but the object graph for that object is huge, containing hundreds of types that would need to be initialized and set. This seems impractical, and I'm looking for a viable solution to this problem. If anyone has ANY kind of tips, hints, solutions, or stories relating to this kind of problem or similar problems, I would be very grateful.

Thanks much.

A: 

You probably have session already closed. Try to keep the session open when data is lazy loaded or if this is not possible, do eager load by specifying lazy="false" attribute on the collection (lazy="true" is the default).

bbmud
+1  A: 

If you are handling the sessions by hand, try passing object ids (row ids in the database) instead of full objects. Then preform a database read when you want to get the full blown ORM object and only keep the ORM object in a limited scope so it could be garbage collected when you were done with it. This would probably save you some memory.

This has a side effect of also limiting the amount of time you need an open session for. As you could open sessions (I would recommend a session factory) and close them as needed. However, I think there may be a significant database hit for opening and closing sessions (I think the underlying transaction is the real problem). You may want to look into JPA, which as far as I understand, doesn't need a transaction for reads. Spring also has some nice features to automate transaction and session management they may want to investigate.

James McMahon
A: 

The most common cause of a LazyInitializationException is that the hibernate session is closed. Keep the hibernate session open and you should be fine.

Please note that if you're using the Spring HibernateTemplate to load objects, the objects that you load will necessarily be detached. If you're building a webapp using Spring MVC, an easy way around this is to use the OpenSessionInViewInterceptor.

Paul Morie