I once needed something similar to that, and I had to use Reflection to solve it. In my case, I was using hql to retrieve the records. Also, this is an approach I created for eager loading records that are defined as lazy loading, so you may want to adapt the first method to not look for a FetchType.LAZY property and always fetch it regardless.
One of the methods I built will "prepare" the lazy fetching. Basically two approaches: using "left join fetch" on the hql for @ManyToOne, and hibernate.initialize() for @OneToMany and @ManyToMany.
So, this first method returns a string with the required "left john fetch"es for the hql, and also builds a list of nToMany fields that have to be called by Hibernate.initialize() after the query is executed.
private String buildLazyFetch(Class<? extends GenericEntity> entityClass, List<String> nToManyFields) {
String lazyFetches = new String();
lazyFetches += " fetch all properties ";
// iterate through all fields looking for lazy loaded relationships
for (Field f : entityClass.getDeclaredFields()) {
ManyToOne manyToOne = f.getAnnotation(ManyToOne.class);
if (manyToOne != null) {
if (manyToOne.fetch().equals(FetchType.LAZY)) {
lazyFetches += " left join fetch t." + f.getName() + " ";
}
}
OneToMany oneToMany = f.getAnnotation(OneToMany.class);
if (oneToMany != null) {
if (oneToMany.fetch().equals(FetchType.LAZY)) {
nToManyFields.add(f.getName());
}
}
ManyToMany manyToMany = f.getAnnotation(ManyToMany.class);
if (manyToMany != null) {
if (manyToMany.fetch().equals(FetchType.LAZY)) {
nToManyFields.add(f.getName());
}
}
}
return lazyFetches;
}
and for after the hql is executed, call:
private void lazyFetchNToMany (List<String> nToManyFields, GenericEntity entity) {
for (String field : nToManyFields) {
try {
Hibernate.initialize(BeanUtils.getProperty(entity, field));
} catch (HibernateException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
I understand this is not exactly what you expected, but it might help you out in case you don't find your desired solution