Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to expose Hibernate Entities as RESTful resources without DTOs?

I am developing a simple webapp which exposes the domain model as RESTful resources. I am planning to use JPA2(Hibernate) with SpringMVC REST support.

While marshalling Hibernate entities into XML/JSON, if the entity is detached it will throw LazyLoadingException for lazy child associations. If the entity is still attached to Hibernate Session it will almost load whole database.

I have tried using Dozer CustomFieldMapper to determine if the property is lazy Hibernate Collection which is not loaded then return NULL.

But if we have bi-directional associations Hibernate eagerly load Many-to-One side and Dozer will try to copy properties which will end up in infinite loop resulting StackOverflow error.

The only work around that I know to resolve this is using DTOs and copying the required properties only into clean POJOs(DTOs) and marshalling then into XML/JSON. But it is terribly painful for complex domain model to copy properties manually.

Is there any other clean/simpler way to (un)marshall Hibernate entities?

like image 534
K. Siva Prasad Reddy Avatar asked Jan 03 '13 08:01

K. Siva Prasad Reddy


1 Answers

I might sound too conservative but I consider using DTOs still a good idea.

The complexity of your mappings is proportional to the granularity of your resources' API, in other words the coarser the more complex.

like image 133
Alessandro Santini Avatar answered Sep 19 '22 13:09

Alessandro Santini