I once needed something similar, and I had to use Reflection to solve it. In my case, I used hql to retrieve the records. Also, this is the approach I created for active boot records that are defined as lazy loading, so you can adapt the first method so you don’t look for the FetchType.LAZY property and always retrieve it independently.
One of the methods I built will “prepare” a lazy choice. There are basically two approaches: using "left join fetch" in 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 hql, and also builds a list of nToMany fields that should be called by Hibernate.initialize () after the query is completed.
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 after executing hql 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 that this is not quite what you expected, but it can help you in case you do not find the solution you need.
source share