I experimented with removing Hibernate specific details from the pojo object (for example, when I need to serialize them and send them to remote computers), and the next one is the code I came up with. Its "initializeAndUnproxy ()" is taken from one of the answers Bozho gave: Converting the Hibernate proxy to a real object , and I changed it to call a recursive method in it.
I would like your comments on this code about its shortcomings. For instance. it will not remove PersistentSet types. So what improvements would you suggest?
static <T> T initializeAndUnproxy(T entity) throws IllegalArgumentException, IllegalAccessException { if(entity == null) { throw new NullPointerException("Entity passed for initialization is null"); } Hibernate.initialize(entity); T ret = entity; if(entity instanceof HibernateProxy) { ret = (T)((HibernateProxy)entity).getHibernateLazyInitializer().getImplementation(); initializeRecursively(ret); } return ret; } static void initializeRecursively(Object entity) throws IllegalArgumentException, IllegalAccessException { Class<?> clazz = entity.getClass(); Field[] fields = clazz.getDeclaredFields(); for(Field field : fields) { field.setAccessible(true); Object obj = field.get(entity); Hibernate.initialize(obj); if(obj instanceof HibernateProxy) { obj = ((HibernateProxy)obj).getHibernateLazyInitializer().getImplementation(); field.set(entity, obj); initializeRecursively(obj); } if(obj instanceof LazyInitializer) { obj = ((LazyInitializer)obj).getImplementation(); initializeRecursively(obj); } } }
source share