Hi,
I'm posting this to get some feedback.
Being fairly well-read in the use of Hibernate I'm definitely aware of the long-conversation and 'session in view' concepts. However, like several of my projects and many posts in this forum, sometimes you just have to have all lazy properties of an entity initialized on the return of some method and sometimes you just want the value-typed properties or can use lazy initialization.
SO, I was faced with writing a separate DAO method for retrieving & initializing every entity type and instead spent some time trying to come up with a method that would do it for any entity type.
One thing of note: The PropertyUtils class is just a nifty helper from Apache Commons BeanUtils library.
Here it is: What do you think? This bad for some reason? More efficient way to do it?
Code:
@SuppressWarnings("unchecked") // We know it will be of the type passed
public <T> T getFull(Class<T> entityType, Serializable id)
{
T entity = (T)getSessionFactory().getCurrentSession().get(entityType, id);
ClassMetadata classMetaData = getSessionFactory().getClassMetadata(entityType);
String[] propNames = classMetaData.getPropertyNames();
for (int i = 0; i < propNames.length; i++){
try {
Hibernate.initialize(PropertyUtils.getProperty(entity, propNames[i]));
} catch (RuntimeException re) { throw (re); }
catch (Exception e) { throw new RuntimeException(e); }
}
return entity;
}
FYI, here's the method that just gets the entity w/o initialization:
Code:
@SuppressWarnings("unchecked") // We know it will be of the type passed
public <T> T get(Class<T> entityType, Serializable id)
{
return (T)getSessionFactory().getCurrentSession().get(entityType, id);
}
Thanks!
Scott