-
1. Re: check if a lazy property is loaded
ablevine1 Jul 11, 2006 9:07 PM (in response to boercher)I'm not exactly sure how this works for lazy-loadable properties that are non-collection based objects, but I bet it's probably pretty similar. For properties that are a collection implementation e.g. List, Set, .. etc., their lazy loaded proxy collections implement the interface org.hibernate.collection.PersistentCollection after they are persisted by the entity manager. To determine if one of these has been loaded yet, you can call the wasInitialized() method. Most likely, the proxy objects that implement lazy-loaded non-collection based properties implement a common interface and have a method that you can call that is similar to wasInitialized().
I see that there is a org.hibernate.proxy.HibernateProxy interface. Perhaps these objects implement that. If so, then you may be able to call
getHibernateLazyInitializer() to get a LazyInitializer and then from that call isUninitialized(), how ever I have not yet tried this. -
2. Re: check if a lazy property is loaded
boercher Oct 24, 2006 6:38 PM (in response to boercher)Thanks for the answer ablevine! It works exactly as you wrote. I've implemented some helper methods that does everything we need:
public static String getObjectDescription(Object o) { if (o instanceof HibernateProxy) { LazyInitializer initializer = ((HibernateProxy) o) .getHibernateLazyInitializer(); return initializer.getEntityName() + "#" + initializer.getIdentifier(); } return o.toString(); }
This one is also nice:public static boolean canBeUsed(Object o) { if (o instanceof HibernateProxy) { LazyInitializer initializer = ((HibernateProxy) o) .getHibernateLazyInitializer(); // if already initialized - use it! if ( ! initializer.isUninitialized()) return true; // if the session still works - use it! return initializer.getSession() != null && initializer.getSession().isOpen(); } return true; }
The ultimative cure for LazyInitializationExceptions is a combination of canBeUsed() and a dedicated service that does something like that:mEm.find(Class.forName(initializer.getEntityName()) , initializer.getIdentifier());