0

I have a very straight-forward webservice that returns an object retrieved from the database. I'm using a spring-data-jpa repository to get the entity, after which, I return the object without any modification.

I have several lazy-loaded relationships in the entity and would like to leave them "unfetched". However, when the webservice marshals the response object, it triggers the lazy fetches and makes additional calls to the database.

I will still need to lazily fetch the data under certain circumstances so I need to be able to dynamically detach/remove/unproxy the object from the control of Hibernate.

I have attempted to use the following method to unproxy the object, but without any luck (my entity is not a HibernateProxy object it seems).

What is the best approach to "un-ORMify" an entity so that I can freely manipulate/serialize the object without triggering data calls.

Community
  • 1
  • 1
Tyler Murry
  • 2,325
  • 3
  • 24
  • 40
  • If the ORM is Hibernate then I think the proxy would be a `HibernateProxy`. what is the type of the proxy you are seeing? I have not tried it did you try typecasting it to `AbstractPersistentCollection` and calling `forceInitialization()` method on that? – Madhusudana Reddy Sunnapu Mar 24 '16 at 03:07
  • why not present some code, showing where the transaction boundary is, and what the class is? Ought to be possible to "detach" an object without loading of certain fields, because other JPA implementations can certainly handle that – Neil Stockton Mar 24 '16 at 07:22
  • If using Hibernate this is a duplicate of https://stackoverflow.com/questions/2216547/converting-hibernate-proxy-to-a-real-entity-object/29004398#29004398 – Jens Schauder Jun 13 '19 at 06:13

1 Answers1

1

I have found that the Data Transfer Objects (DTO) often have different requirements than the Entity Objects, and for this reason I just write custom DTO objects. The constructor is typically an Entity Object and it just copies the initialized fields it needs. Then there is no lazy initialization exception and what the other side is getting doesn't include unused fields. Much better than trying to hack up the whole proxy stuff, IMHO.

Helpful link: Difference between Transfer objects and Domain objects

Community
  • 1
  • 1
K.Nicholas
  • 8,797
  • 4
  • 34
  • 53
  • I ended up going with this route. I agree with you that it seemed hacky to try and fool the proxy methods and this seems like the better option. Additionally, it allowed me to remove all my non-entity-related annotations out to the DTO where I think they should be rather than clobbering a data model and webservice reponse object together. – Tyler Murry Mar 30 '16 at 01:43