Remove Hibernate from pojo's?

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); } } } 
+4
source share
2 answers

I do not see the point. If I understand correctly

  • the remote client still has to have Hibernate jars in its classpath,
  • all of this means that recursively initialize all toOne associations of an object

That way, you are likely to still have lazy boot exceptions due to uninitialized proxies in collections. You will probably transfer more data than necessary to the remote client, which probably does not need all toOne associations and all initialized collections. Of course, this will lead to the creation of a large number of additional database queries.

My point is that

  • the client is closely connected to the server, may depend on Hibernate and uses separate Hibernate objects. And you should only initialize what you need to initialize with the client.
  • or the ios client is loosely coupled and may not be dependent on Hibernate, and you should then pass in common DTOs and convert your objects to DTOs.
-1
source

Perhaps cloning objects? Clone every object that you want to serialize and send over the network. You need to write a cloning method, although you will not have an additional DTO class for each POJO

+1
source

Source: https://habr.com/ru/post/1386652/


All Articles