For our projects I developed a so called preload pattern. In short, with the preload pattern the client tells the backend which entities to preload via an additional parameter. At this point I don't want to discuss the pros and cons of the preload pattern. For us the pattern works perfectly well for all kind of GUIs.
Below is the most important code fragment of a new implementation. My question is if the usage of
Hibernate.initialize() within the
onPostLoad() method is ok or could there be any drawbacks which I don't overlook at the moment?
Code:
public class PreloadEventListener extends DefaultPostLoadEventListener {
private static ThreadLocal<Preload[]> preloadsThreadLocal = new ThreadLocal<Preload[]>();
public static void setPreloads(Preload[] preloads) {
preloadsThreadLocal.set(preloads);
}
public static void clearPreloads() {
preloadsThreadLocal.set(null);
}
protected Object callGetter(Object entity, Preload preload) {
try {
// Call the getter on the entity via reflection
return preload.callGetter(entity);
} catch (Exception ex) {
String msg = "Can't invoke getter for property: " + preload.getProperty();
throw new PreloadException(msg, ex);
}
}
public void onPostLoad(PostLoadEvent event) {
Object entity = event.getEntity();
Preload[] preloads = preloadsThreadLocal.get();
if( preloads != null ) {
for (Preload preload : preloads) {
if (preload.getModelClass().isInstance(entity)) {
Object getterResult = callGetter(entity, preload);
Hibernate.initialize(getterResult);
}
}
}
super.onPostLoad(event);
}
}
Preload machanism is activated in the GenericDAO like so:
Code:
...
PreloadEventListener.setPreloads(preloads);
result = crit.list();
PreloadEventListener.clearPreloads();
...
If somebody is interested in the full code please let me know.