i tend to initialize collections at the service level, where I also save transaction processing. That way, I can have a method in my BaseDAO that allows me to initialize any collection of any Entity in my projects using reflection, passing the collection names to a method that should be looked forward to (initialized):
public <T extends Object> T getEntity(Class<T> clazz,long id,String[] collectionsToBeInitialized){ T entity=(T) this.getCurrentSession().createCriteria(clazz).add(Restrictions.idEq(id)).setFetchMode(collectionsToBeInitialized[0], FetchMode.JOIN).uniqueResult(); int length=collectionsToBeInitialized.length; for (int idx=1;idx<length;idx++){ String collectionName=collectionsToBeInitialized[idx]; try { Method m = clazz.getMethod("get" + collectionName.substring(0, 1).toUpperCase() + collectionName.substring(1),(Class<T>) null); Hibernate.initialize(m.invoke(entity,(Object[]) null)); } catch (NoSuchMethodException e) { LOG.error("Could not initialize collection " + collectionName + " of class Event", e); } catch (InvocationTargetException e) { LOG.error("Could not initialize collection " + collectionName + " of class Event", e); } catch (IllegalAccessException e) { LOG.error("Could not initialize collection " + collectionName + " of class Event", e); } } return entity; }
then you can initialize any collection from the service level using this method:
MyEntity ent=getEntity(MyEntity.class,id,new String[]{"collection1","collection2"});
More detailed example: http://objecthunter.congrace.de/tinybo/blog/articles/69
fasseg
source share